简体   繁体   English

无法迁移 ASP.NET 核心 API 中的第二个数据库

[英]Cannot migrate second database in ASP.NET Core API

I'm trying to use two different databases in one api.我试图在一个 api 中使用两个不同的数据库。

These are the contexts:这些是上下文:

public class DatabaseOneDBContext : DbContext, IDatabaseOneDBContext
{
    public DatabaseOneDBContext(DbContextOptions<DatabaseOneDBContext> options)
        : base(options)
    {

    }

    public DbSet<Alena> Alena { get; set; }

    public async Task<int> SaveChangesAsyncOne()
    {
        return await base.SaveChangesAsync(); 
    }
}

public class DatabaseTwoDBContext : DbContext, IDatabaseTwoDBContext
{
    private readonly IDatabaseTwoDBContext _context;

    public DatabaseTwoDBContext(IDatabaseTwoDBContext context)
    {
        this._context = context;
    }

    public DbSet<Cortana> Cortana { get; set; }

    public async Task<int> SaveChangesAsyncTwo()
    {
        return await base.SaveChangesAsync(); 
    }
}

appsettings.json appsettings.json

"ConnectionStrings": {
    "ConnectionDB1": "Server=.\\SQLEXPRESS;Database=DatabaseOne;Trusted_Connection=True;MultipleActiveResultSets=true",
    "ConnectionDB2": "Server=.\\SQLEXPRESS;Database=DatabaseTwo;Trusted_Connection=True;MultipleActiveResultSets=true"
},

Startup.cs启动.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Forecast.DatabaseOne;
using Forecast.DatabaseOne.Contracts;
using Forecast.ServiceOne.Contracts;
using Forecast.ServiceOne;
using Serilog;
using Forecast.DatabaseTwo;
using Forecast.DatabaseTwo.Contracts;
using Forecast.ServiceTwo.Contracts;
using Forecast.ServiceTwo;

namespace Forecast.Web
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(Configuration)
                .CreateLogger();
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DatabaseOneDBContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("ConnectionDB1"),
                    ef => ef.MigrationsAssembly("Forecast.DatabaseOne")));

            services.AddScoped<IDatabaseOneDBContext>(provider => provider.GetService<DatabaseOneDBContext>());

            services.AddDbContext<DatabaseTwoDBContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("ConnectionDB2"),
                    ef => ef.MigrationsAssembly("Forecast.DatabaseTwo")));

            services.AddScoped<IDatabaseTwoDBContext>(provider => provider.GetService<DatabaseTwoDBContext>());

            services.AddTransient<IAlenaService, AlenaService>();
            services.AddTransient<ICortanaService, CortanaService>();

            services.AddApiVersioning(apiVerConfig =>
            {
                apiVerConfig.AssumeDefaultVersionWhenUnspecified = true;
                apiVerConfig.DefaultApiVersion = new ApiVersion(new DateTime(2022, 1, 22));
            });

            services.AddHealthChecks()
                .AddDbContextCheck<DatabaseOneDBContext>();

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1a", new Microsoft.OpenApi.Models.OpenApiInfo
                {
                    Title = "ForecastService - Alena Web API",
                    Version = "v1a",
                    Description = "test service"
                });
            });

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseHealthChecks("/checkhealth");

            app.UseSwagger();
            app.UseSwaggerUI(options =>
                {
                    options.SwaggerEndpoint("/swagger/v1a/swagger.json", "Alena API v1a");
                });
        }
    }
}

When I use this当我使用这个

add-migration -context DatabaseOneDBContext 
update-database -context DatabaseOneDBContext 

it works and default project is DatabaseOne , but when I try to do the same thing for DatabaseTwoDBContext (I change the default project to DatabaseTwo ), it just sleeps the process and I have to restart my PC so I can try again.它可以工作,默认项目是DatabaseOne ,但是当我尝试对DatabaseTwoDBContext做同样的事情时(我将默认项目更改为DatabaseTwo ),它只是让进程休眠,我必须重新启动我的电脑,这样我才能再试一次。

Help me solve this帮我解决这个

it seems to me that you need to replace this line with the same one as in the first context在我看来,您需要将此行替换为与第一个上下文中相同的行

Try change this尝试改变这个

  private readonly IDatabaseTwoDBContext _context;

  public DatabaseTwoDBContext(IDatabaseTwoDBContext context)
  {
      this._context = context;
  }

To this对此

public DatabaseOneDBContext(DbContextOptions<DatabaseTwoDBContext> options)
    : base(options)
{

}

Perhaps the second context is recursively trying to resolve the dependency IDatabaseTwoDBContext in constructor也许第二个上下文是递归地尝试解决构造函数中的依赖项 IDatabaseTwoDBContext

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM