EF Core Migrations with multiple DbContexts on single database
I think your problem is just two Context try to use same migration history table
try specific your migration history table for each
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer(
connectionString,
x => x.MigrationsHistoryTable("__MyMigrationsHistoryForDBContextA", "mySchema"));
it should be fix
Custom Migrations History Table
Related videos on Youtube
Chris Pickford
Full stack contract developer living in the South West UK.
Updated on August 06, 2022Comments
-
Chris Pickford over 1 year
I have an issue attempting to use Migrations in a ASP.NET Core solution using EF Core where there are multiple
DbContext
that share the same SQL database.In my application startup method I'm getting a reference to each context and calling the
context.Database.Migrate()
method. However as both of these contexts are pointing to the same underlying database I'm getting the error:There is already an object named '__EFMigrationsHistory' in the database.
Here's a 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"); }); }
Note that each
DbContext
exists in a separate assembly in which the Migrations are configured.I am able to manually execute the respective migrations with the
Update-Database
CLI tool but it doesn't seem to work as part of my app startup code.Is there a way to execute migrations on both contexts at runtime and bypass the
__EFMigrationsHistory
table creation if already exists? -
Tseng almost 6 yearsMultiple Contexts using the same database shouldn't be an issue as pointed by @bricelam in this comment. So you are maybe doing something "funky" and the two contexts share the same migration IDs?
-
Asakuraa Ranger almost 6 yearsI mean just separate migration history for each context it will be fixed, because two context try to create same migration history table name and the two table with same name same schema are not allowed
-
Joe Audette almost 6 yearsI have multiple dbcontexts from different assemblies working fine in my projects and they all use the same migration history table, seems weird to have to do that.
-
Tseng almost 6 yearsI agree with @JoeAudette, something strange seems about that setup. While it max fix the immediate problem, it won't fix the root of problem of it.
-
Chris Pickford almost 6 years@JoeAudette How are you executing the migrations in your scenario?
-
Joe Audette almost 6 years