auto create database in Entity Framework Core

前端 未结 5 750
南笙
南笙 2020-11-29 17:43

My application which is being ported to .NET core will use the new EF Core with SQLite. I want to automatically create the database and table structures when the app is firs

5条回答
  •  暖寄归人
    2020-11-29 18:06

    For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

    public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args).Build();
            using (var serviceScope = host.Services.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetRequiredService();
                context.Database.Migrate();
            }
            host.Run();
        }
    
        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup();
    }
    

提交回复
热议问题