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

标签 c# entity-framework asp.net-core entity-framework-core entity-framework-migrations

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

在我的应用程序启动方法中,我获取对每个上下文的引用并调用 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 表创建(如果已经存在)?

最佳答案

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

尝试为每个特定的迁移历史表

protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(
    connectionString,
    x => x.MigrationsHistoryTable("__MyMigrationsHistoryForDBContextA", "mySchema"));

应该修复

Custom Migrations History Table

关于c# - 单个数据库上具有多个 DbContext 的 EF Core 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50527157/

相关文章:

asp.net-mvc - 无法在 Entity Framework 模型中的 MVC 4 模板中使用 UserProfile?

c# - Javascript 中的日期选择器和时间选择器条件

c# - OracleParameter 和 IN 子句

c# - 在 WinRT 中从 C# 解析 JSON

c# - 作用域/ transient 依赖注入(inject)确保返回相同的接口(interface)和实现实例

c# - 如何手动取消 .NET core IHostedService 后台任务?

c# - 在 Entity Framework 存储库中使用选择器

entity-framework - 如何记录 SQL 查询

c# - ASP.NET Core 中全局过滤器的顺序

c# - 如何在没有数据库的情况下在 ASP.NET Core 中创建一个简单的登录并授权 Controller 访问