ASP - Core Migrate EF Core SQL DB on Startup

后端 未结 11 945
故里飘歌
故里飘歌 2020-12-01 02:32

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

11条回答
  •  醉酒成梦
    2020-12-01 03:11

    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();
    

提交回复
热议问题