Tuesday, October 10, 2017

EF Core Automatic Migrations

As you might know and as of today, for Entity Framework Core, Microsoft does not support Automatic Database Migrations as in Entity Framework Full. The reasons are described in this Issue. But it doesn't stop you from configuring automatic migrations by your own. You can just write something like below and call this inside Startup -> Configure method passing the IApplicationBuilder.
private static void InitializeMigrations(IApplicationBuilder app)
{
    using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
        dbContext.Database.Migrate();
 
        // TODO: Use dbContext if you want to do seeding etc.
    }
}
Happy Coding.

Regards,
Jaliya