EF Migration tasks in the Program.cs – The good and the Ugly
Program.cs of any core project (especially ASP.Net Core) is our first starting point to get some necessary work out of the wrong. In this case EF DB Migrations. You know that EF thing where you keep your attached DB tables in sync with your data models? (or in some cases… mess up your existing database).
Life in program.cs normally starts here:
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }
But let’s consider this:
public class Program { public static async Task Main(string[] args) { IWebHost webHost = CreateWebHostBuilder(args).Build(); // Create a new scope using (var scope = webHost.Services.CreateScope()) { // Get the DbContext instance var myDbContext = scope.ServiceProvider.GetRequiredService<MyDbContext>(); //Do the migration asynchronously await myDbContext.Database.MigrateAsync(); } // Run the WebHost, and start accepting requests // There's an async overload, so we may as well use it await webHost.RunAsync(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); }
What the? So what is going on here… Well, basically we are injecting our EF DB Migration process between the creating of our web app (Build) and the actual Running of the site… You know that period of time when processes are defined and setup and actually begin listening on the wire.
Have a look at this article….
https://andrewlock.net/running-async-tasks-on-app-startup-in-asp-net-core-part-1/