[英]How to create database with code first approach with initializer
I want to create database if is not exists in Entity framework core.如果实体框架核心中不存在数据库,我想创建数据库。 We could use initializer with code first approach in Entity Framework using Database Initialization Strategies without migrations
as in the link below我们可以在实体框架中使用带有代码优先方法的初始化程序,使用数据库初始化策略,无需migrations
,如下面的链接所示
CreateDatabaseIfNotExists
DropCreateDatabaseIfModelChanges
DropCreateDatabaseAlways
https://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx https://www.entityframeworktutorial.net/code-first/database-initialization-strategy-in-code-first.aspx
How to do this in Entity Framework Core and.Net Core 3.1如何在 Entity Framework Core 和 .Net Core 3.1 中执行此操作
One way you can achieve this, is by adding the following code in your Startup.cs - Configure method实现此目的的一种方法是在 Startup.cs - Configure 方法中添加以下代码
public void Configure(... )
{
//....
var context = app.ApplicationServices.GetService<YourDbContext>();
context.Database.Migrate();
// To Delete
context.Database.EnsureDeleted();
}
Applies any pending migrations for the context to the database.将上下文的任何挂起迁移应用到数据库。 Will create the database if it does not already exist.如果数据库尚不存在,将创建该数据库。
Alternative, there's another pre-condition that you can use:或者,您可以使用另一个前提条件:
if(context.Database.EnsureCreated()) { // your code here...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.