Is it possible to have my ASP Core Web API ensure the DB is migrated to the latest migration using EF Core? I know this can be done through the command line, but I want to
Based on chintan310's answer, here is how I migrate the database. This ensures separation of database-related tasks into Program.cs:
public static void Main(string[] args)
{
var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetService();
context.Database.Migrate();
var seeder = scope.ServiceProvider.GetService();
seeder.Seed().Wait();
}
catch (Exception ex)
{
var logger = services.GetRequiredService>();
logger.LogError(ex, "An error occurred seeding the DB.");
}
}
host.Run();
}
private static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup()
.Build();