We had upgraded to EF Core 6.0 for a while now but we haven’t had any schema change with migrations since before the upgrade. One of the recent changes had a migration and we noticed that the migration was never run.
We tested other projects that also had upgraded to EF Core 6.0 and they looked good. All the recent migrations ran correctly.
This is how we added the DB context in Startup.cs and ran the migrations
services
.AddEntityFrameworkSqlServer()
.AddDbContextPool<SampleDbContext>((sp, options) =>
{
options.UseSqlServer(configuration.GetConnectionString("Sample"),
sql => sql.EnableRetryOnFailure());
});
var serviceProvider = services.BuildServiceProvider();
using var serviceScope = serviceProvider.CreateScope();
var context = serviceScope.ServiceProvider.GetService<SampleDbContext>();
context.Database.Migrate();
When we were debugging this, we had a break point on the last line and a break point in the new migration file. We saw that it hit the first break point but never hit the one in the migration file, clearly did not run it.
After a whole lot of research and trying different things, we found 2 things that solved this issue
- Adding Microsoft.EntityFrameworkCore.Design package to the start up project that runs the migration.
- Explicitly specify the migration assembly
services
.AddEntityFrameworkSqlServer()
.AddDbContextPool<SampleDbContext>((sp, options) =>
{
var migrationAssembly = typeof(SampleDbContext)
.GetTypeInfo()
.Assembly
.GetName()
.Name;
options.UseSqlServer(configuration.GetConnectionString("Sample"),
sql =>
{
sql.EnableRetryOnFailure();
sql.MigrationsAssembly(migrationAssembly);
});
});
If you don’t want to reference Microsoft.EntityFrameworkCore.Design in the start up project that runs the migration, maybe due to it being a Web API and not want to directly reference EF, you can opt for option 2.