I am using Entity Framework Code First approach with AutomaticMigrationsEnabled = true:
Database.SetInitializer(new MigrateDatabaseToLatestVersi
Microsoft addresses migrations at runtime, here: https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/?tabs=vs#apply-migrations-at-runtime
For example, you can do this in Program.cs: (tested working in .NET 5.0 preview)
public static void Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
MigrateDatabase(host);
host.Run();
}
private static void MigrateDatabase(IHost host)
{
using var scope = host.Services.CreateScope();
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService();
context.Database.Migrate();
}
catch (Exception ex)
{
var logger = services.GetRequiredService>();
logger.LogError(ex, "An error occurred creating the DB.");
}
}