简体   繁体   English

如何使用带有初始化程序的代码优先方法创建数据库

[英]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.

相关问题 如何使用实体框架代码优先方法正确创建数据库 - How to correctly create a database using entity framework code first approach 数据库未使用代码优先方法在 blazor 中创建 - database not create in blazor using code first approach 如何混合数据库优先和代码优先的方法 - How to mix Database first and Code first approach 使用EF Code First的数据库初始化程序 - Database initializer with EF Code First 如何指定EF代码优先方法在其中创建数据库的自定义文件夹路径? - How to specify a custom folder path in which EF code-first approach create a database? 如何通过 .NET CORE 2.2 中的代码优先方法使用 linq2db 在 Microsoft SQL Server 中创建数据库 - How to create database in Microsoft SQL Server using linq2db by code first approach in .NET CORE 2.2 如何使用数据库迁移和EF 4.3与代码第一种方法来创建关系表? - How to use Database Migrations and EF 4.3 with a code first approach to create relationship tables? 如何创建数据库优先方法精确类项目 - How to create database first approach exact class project 如何从 EF Core 代码优先方法创建存储过程? - How to create a stored procedure from EF Core code first approach? 呈现存储在数据库代码优先方法中的Pdf - Rendering a Pdf that is stored in the Database Code First Approach
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM