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
I followed the IStartupFilter
approach to have a generic way for migrating any context.
public class DataContextAutomaticMigrationStartupFilter : IStartupFilter
where T : DbContext
{
///
public Action Configure(Action next)
{
return app =>
{
using (var scope = app.ApplicationServices.CreateScope())
{
scope.ServiceProvider.GetRequiredService().Database.SetCommandTimeout(160);
scope.ServiceProvider.GetRequiredService().Database.Migrate();
}
next(app);
};
}
}
Now we're able to register the DataContexts and migration in the following way:
1st context
services.AddDbContext(options => options.UseSqlServer(configuration.GetConnectionString("ConsumerConnection")), ServiceLifetime.Transient);
services.AddTransient>();
2nd context
services.AddDbContext(options => options.UseSqlServer(configuration.GetConnectionString("UserConnection")), ServiceLifetime.Transient);
services.AddTransient>();
..and so on..
The culprit of IStartupFilter
is that it only allows synchronous execution of code. For database migrations this is not an issue since we have a synchronous Migrate()
method.