Automatically migrate your Entity Framework Core managed database on ASP.NET Core application start

March 20, 2018, (updated on September 20, 2018), Software Development

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.


Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax

This site uses Akismet to reduce spam. Learn how your comment data is processed.