开发手册 欢迎您!
软件开发者资料库

.NET Core EF(Entity Framework) Core 自动创建数据库

之前的项目要移植到.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().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService();
context.Database.Migrate();
}
//省略不相关代码...
}

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

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

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

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

context.Database.EnsureDeleted();

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