Just to add to @Travis's excellent answer, the preferred Main method syntax has changed a bit compared to Core 2.1 and now the Main method now has CreateWebHostBuilder instead of BuildWebHost .
The revised code for invoking the extension method is shown below.
NB: order is important here, the Build method returns WebHost , which extends the extension method, so you need to call the migrate method after Build() and before Run() ):
public static void Main(string[] args) { CreateWebHostBuilder(args) .Build() .MigrateDatabase() .Run(); }
There is more than one DbContext in our project, so I changed the extension method to a universal method that can accept any type of DbContext :
public static IWebHost MigrateDatabase<T>(this IWebHost webHost) where T:DbContext { var serviceScopeFactory = (IServiceScopeFactory)webHost .Services.GetService(typeof(IServiceScopeFactory)); using (var scope = serviceScopeFactory.CreateScope()) { var services = scope.ServiceProvider; var dbContext = services.GetRequiredService<T>(); dbContext.Database.Migrate(); } return webHost; }
Then you can combine calls to transfer different contexts:
CreateWebHostBuilder(args) .Build() .MigrateDatabase<ApiAuthDbContext>() .MigrateDatabase<MainDbContext>() .MigrateDatabase<SomeOtherDbContext>() .Run();
source share