自动创建数据库必须在NuGet 中安装一下三个库

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

dotnet ef migrations add NewColum --新增migrations
dotnet ef database update--跟新数据库
dotnet ef migrations add Addrs--新增一个migrations
dotnet ef database update
dotnet ef datebase update NewColum--根据newcolum跟新数据库
dotnet ef migrations remove--删除最新未使用的migrations

之前的项目要移植到.NET Core中,移植之后要使用EF Core,想要自动创建数据库和表结构,查找一些资料和文档,有两种方法一种是手动执行命令创建,另一种是通过代码,在首次使用时自动创建,下面就分享一下这两种方法。

 

1、.NET Core中手动执行命令创建

dotnet ef migrations add MyFirstMigration
dotnet ef database update

2、通过.NET Core代码,首次使用时自动创建

1)如果已经创建了迁移,则可以在Startup.cs中执行它们,如下所示。

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.Migrate();
      }
      //省略不相关代码...
 }

 

 

使用添加迁移的表和数据创建数据库

 

2)如果不迁移数据,只是需要在首次运行时,完全按照在上下文类中的DbContext模型来创建数据库,则可以使用:

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
 {
      using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
      {
            var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
            context.Database.EnsureCreated();
      }
      //省略不相关代码...
 }

如果需要在创建数据库之前删除它,则可以使用下面代码:

context.Database.EnsureDeleted();

参考文档:http://docs.identityserver.io/en/release/quickstarts/8_entity_framework.html?highlight=entity

更多推荐