Search code examples
entity-frameworkentity-framework-core

Migration set per DbContext


I have two DbContexts in one project which are both mapped to 2 different Schemas. I've set the MigrationHistoryTable for each DbContext to be stored in each corresponding schema.

services.AddDbContext<Context1>(options =>
{
    options.UseNpgsql(dataSource, sqlOptions =>
    {
        sqlOptions.MigrationsHistoryTable("__EFMigrationsHistory", "Schema1");
        sqlOptions.MigrationsAssembly(Assembly.GetAssembly(typeof(Context1))?.FullName);
    });
});

services.AddDbContext<Context2>(options =>
{
    options.UseNpgsql(dataSource, sqlOptions =>
    {
        sqlOptions.MigrationsHistoryTable("__EFMigrationsHistory", "Schema2");
        sqlOptions.MigrationsAssembly(Assembly.GetAssembly(typeof(Context2))?.FullName);
    });
});

I want to have 2 different Migration set for each dbcontext. The problem is when I add migration for any dbcontext (ex: add-migration InitialMigration -c Context1), it creates a subfolder under Migrations with the name of the db context and include both context changes.

Is there a way to have Context1 migrations under Migrations/Context1Db and Context2 migrations under Migrations/Context2Db without creating two different migration assemblies?


Solution

  • The problem was that the entity configurations was registered inside the dbcontext as modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly()); which picked up all entity configurations from both dbContexts.

    The solution was to specify the entity configurations manually like modelBuilder.ApplyConfiguration(new XyzEntityTypeConfiguration());