单个数据库上具有多个 DbContext 的 EF Core 迁移

EF Core Migrations with multiple DbContexts on single database

我尝试在使用 EF Core 的 ASP.NET Core 解决方案中使用迁移时遇到问题,其中有多个 DbContext 共享同一个 SQL 数据库。

在我的应用程序启动方法中,我获取了对每个上下文的引用并调用了 context.Database.Migrate() 方法。然而,由于这两个上下文都指向同一个底层数据库,我收到了错误:

There is already an object named '__EFMigrationsHistory' in the database.

这是一个 MCVE:

class DbContextA : DbContext {}
class DbContextB : DbContext {}

static void Main(string[] args)
{
  var contextA = GetContextFromDIContainer<DbContextA>();
  var contextB = GetContextFromDIContainer<DbContextB>();

  contextA.Database.Migrate();
  contextB.Database.Migrate();
}

void ConfigureServices(IServiceCollection services)
{
  services.AddDbContext<DbContextA>(opt =>
  {
    opt.UseSqlServer("connectionstring");
  });

  services.AddDbContext<DbContextB>(opt =>
  {
    opt.UseSqlServer("connectionstring");
  });
}

请注意,每个 DbContext 都存在于配置迁移的单独程序集中。

我可以使用 Update-Database CLI 工具手动执行相应的迁移,但它似乎无法作为我的应用程序启动代码的一部分。

有没有办法在运行时在两个上下文中执行迁移并绕过 __EFMigrationsHistory table 创建(如果已经存在)?

我认为你的问题只是两个上下文尝试使用相同的迁移历史table

尝试为每个

指定您的迁移历史table
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(
    connectionString,
    x => x.MigrationsHistoryTable("__MyMigrationsHistoryForDBContextA", "mySchema"));

应该修复

Custom Migrations History Table