Migrating at runtime with Entity Framework Core

c# database-migration entity-framework entity-framework-core

Question

I'm porting a PHP/Illuminate application to ASP.NET Core/EF Core. Part of it consists of a Wordpress-like install process that asks for database credentials and then creates the necessary tables for the app to function. Essentially, I want to run some sort of migration at runtime like I can with Illuminate's schema builder.

I found the reference for the Microsoft.EntityFrameworkCore.Migrations namespace which seems related to what I want to do, but I can't seem to find any documentation or best practices on how to actually use it. I imagine I could write raw SQL queries and execute those, but I'd much rather work with a nice, strongly typed API if possible.

Is this possible with EF Core, and does anyone have some suggestions on how to do it? I'm currently using the Pomelo MySQL provider if that makes any difference.

1
5
12/11/2016 8:37:00 PM

Accepted Answer

Assuming you already have migrations prepared, something like this in your Startup class will do the trick:

public void ConfigureServices(IServiceCollection services)
{
    // Wire up whatever your equivalent DbContext class is here
    services.AddDbContext<ApplicationDbContext>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        scope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
    }
}
11
12/12/2016 2:18:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow