If you use Entity Framework Core with migrations in your ASP.NET Core application and want to ensure that the database structure always matches the currently running application, you can simply migrate the database on application startup. This way you just have to redeploy your application and everything like migrating the data, change the schemas, etc. is done when the application is restarted.
To do an automatic migration, register your DbContext
implementation in the ASP.NET Core’s dependency injection system - the same way as it is already recommended by Microsoft. Because there is no active injection scope in the Configure()
method, we have to create a new one by using the IServiceScopeFactory
. With this scope, we can just resolve your DbContext
implementation instance and call Migrate()
on the database object:
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDbContext>(...);
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
UpdateDatabase(app);
...
}
private static void UpdateDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
using (var context = serviceScope.ServiceProvider.GetService<MyDbContext>())
{
context.Database.Migrate();
}
}
}
}
This article just shows how to do this automatic migration on application startup, I don’t say that this is necessarily a good idea: Depending on your environment, it may be better to separate the migration from application startup - for example into an independent staging step in your CD pipeline which runs before application deployment.
Rico Suter
SOFTWARE ENGINEERING
EDIT
ASP.NET Core Entity Framework Entity Framework Core Entity Framework Migrations