.NET Core EF(Entity Framework) Core 自动创建数据库
时间:2022-08-20
1、.NET Core中手动执行命令创建
dotnet ef migrations add MyFirstMigration
dotnet ef database update
2、通过.NET Core代码,首次使用时自动创建
1)如果已经创建了迁移,则可以在Startup.cs中执行它们,如下所示。
public void Conp(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 Conp(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
特别声明:本站部分内容收集于互联网是出于更直观传递信息的目的。该内容版权归原作者所有,并不代表本站赞同其观点和对其真实性负责。如该内容涉及任何第三方合法权利,请及时与824310991@qq.com联系,我们会及时反馈并处理完毕。