如何在.NET 7中使用Entity Framework Core自动创建数据库。

huangapple go评论94阅读模式
英文:

How to auto create a database using Entity Framework Core in .Net 7

问题

我想让我的.NET 7应用程序在启动时创建数据库(如果不存在)。

我正在使用Entity Framework Core。

似乎有两种冲突的方法:

选项#1:

context.Database.EnsureCreated()

我听说这种方法无法与数据库迁移一起使用,而且难以稍后将它们添加到以这种方式创建的数据库中。似乎很受欢迎。也许用于测试?

选项#2:

context.Database.Migrate()

这应该只运行现有的数据库迁移,对吗?

我参与过的所有专业应用程序都使用了迁移,所以这似乎是正确的方法。

另外,我们应该在哪里添加这段代码?是在实体的DbContext内还是在Program.cs内?

哪个选项更好,你会使用什么代码来实现它?

谢谢。

英文:

I want my .NET 7 app to boot up and create a database if one does not exist.

I am using Entity Framework Core.

There seems to be 2 conflicting methods:

Option #1:

context.Database.EnsureCreated()

I'm told this method will not work with database migrations, and it is difficult to add them to a database created this way later on. Seems to be popular. Maybe used for testing?

Option #2:

context.Database.Migrate()

This should just run your existing database migrations right?

All the professional app's I've been involved with used migrations, so it seems like this is the way to go.

Also, where do we add this code? Inside entity's DbContext or inside Program.cs ?

Which option is better and what code would you use to implement it?

Thanks

答案1

得分: 2

它们用于不同的目标,EnsureCreated 用于初始创建(通常在本地开发环境中在 EnsureDeleted 之后使用,以从头开始重新创建)。从文档中:

  • 如果数据库存在并且有任何表,则不执行任何操作。不会采取任何措施来确保数据库架构与 Entity Framework 模型兼容。
  • 如果数据库存在但没有任何表,则使用 Entity Framework 模型来创建数据库架构。
  • 如果数据库不存在,则创建数据库并使用 Entity Framework 模型来创建数据库架构。

而且:

请注意,此 API 使用迁移来创建数据库。此外,使用此方法创建的数据库不能以后使用迁移来更新。

如果目标是通过迁移来管理更改,并将数据库带到当前状态,那么 Migrate 是你的选择。从文档中:

将上下文的任何待处理迁移应用于数据库。如果数据库不存在,它将创建数据库。

请注意,此 API 与 EnsureCreated() 是互斥的。EnsureCreated 不使用迁移来创建数据库,因此使用此方法创建的数据库不能以后使用迁移来更新。

英文:

They are for different goals, EnsureCreated is used for initial creation (usually I use it after EnsureDeleted on local dev environment to recreate from scratch). From the docs:

> -If the database exists and has any tables, then no action is taken. Nothing is done to ensure the database schema is compatible with the Entity Framework model.
> -If the database exists but does not have any tables, then the Entity Framework model is used to create the database schema.
> -If the database does not exist, then the database is created and the Entity Framework model is used to create the database schema

And :

> Note that this API does not use migrations to create the database. In addition, the database that is created cannot be later updated using migrations.

If the goal is to manage changes (via migrations) and to bring the database to the current state then Migrate is your choice . From the docs:

> Applies any pending migrations for the context to the database. Will create the database if it does not already exist.

> Note that this API is mutually exclusive with EnsureCreated(). EnsureCreated does not use migrations to create the database and therefore the database that is created cannot be later updated using migrations.

答案2

得分: 2

基于这个链接,提供了完整的解释。这是对你问题的这部分的答案。

"还有,我们应该在哪里添加这段代码?在实体的 DbContext 中还是在 Program.cs 中?"

你可以将它添加到 program.cs 文件中,如下所示:

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
   // 用你的数据库上下文名称替换 DataContext
   var dataContext = scope.ServiceProvider.GetRequiredService<DataContext>();
   dataContext.Database.Migrate();
}

或者更干净的方式是创建一个扩展方法:

首先创建如下的类:

public static class PrepDb
{
    public static void ApplyMigration(this IApplicationBuilder app)
    {
        using var scope = app.ApplicationServices.CreateScope();
        // 用你的数据库上下文名称替换 DataContext
        var dataContext = scope.ServiceProvider.GetRequiredService<DataContext>();
        dataContext.Database.Migrate();
    }
}

然后在 program.cs 文件中使用如下方式:

var app = builder.Build();

app.ApplyMigration();
英文:

Based on this link, complete explanations are provided. This is the answer for this part of your question

"Also, where do we add this code? Inside entity's DbContext or inside Program.cs ?"

You can add it in the program.cs file as shown below:

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
   //replace DataContext with your Db Context name
   var dataContext = scope.ServiceProvider.GetRequiredService<DataContext>();
   dataContext.Database.Migrate();
}

or cleaner way is create an Extension Method :

first create class as follows :

public static class PrepDb
{
    public static void ApplyMigration(this IApplicationBuilder app)
    {
        using var scope = app.ApplicationServices.CreateScope();
        //replace DataContext with your Db Context name
        var dataContext = scope.ServiceProvider.GetRequiredService<DataContext>();
        dataContext.Database.Migrate();
    }
}

and in program.cs file use as follows :

 var app = builder.Build();

 app.ApplyMigration();

huangapple
  • 本文由 发表于 2023年8月5日 14:43:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76840447.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定