13

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 Answer 1

24

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();
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer. This solution seems to require that the __EFMigrationsHistory table exists before running Migrate(), which cannot be guaranteed in my use case (assume an existing database with no tables). Is there a way around this? For instance, could I run the actual schema building code manually? I should note that maintaining migration history and making further migrations is not required for this project.
I haven't used it personally, but the EnsureCreated method may do what you're looking for. It looks like it bypasses the migrations system entirely. learn.microsoft.com/en-us/ef/core/api/…
Just side note: Database.Migrate() does not require history table to exist before but it will create it for you for the first time. It is used to track the migrations applied in case if you want to make changes to database in future. If you just want schema and tables for first time and never going to update it then you can use context.Database.EnsureCreated() as @BradMelanson suggested.
Of course assuming you have using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; somewhere, because they are extension methods...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.