如何以及在何处调用 Database.EnsureCreated 和 Database.Migrate? [英] How and where to call Database.EnsureCreated and Database.Migrate?

查看:36
本文介绍了如何以及在何处调用 Database.EnsureCreated 和 Database.Migrate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ASP.NET MVC 6 应用程序,我需要调用 Database.EnsureCreatedDatabase.Migrate 方法.

I have a ASP.NET MVC 6 application, and i need to call the Database.EnsureCreated and Database.Migrate methods.

但是我应该在哪里打电话给他们?

But where should I call them?

推荐答案

我觉得这个问题很重要,应该好好回答!

I think this is an important question and should be well answered!

什么是 Database.EnsureCreated?

context.Database.EnsureCreated() 是新的 EF 核心方法,可确保上下文的数据库存在.如果存在,则不执行任何操作.如果它不存在,则创建数据库及其所有模式,并确保它与此上下文的模型兼容.

context.Database.EnsureCreated() is new EF core method which ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created and also it ensures it is compatible with the model for this context.

注意:此方法不使用迁移来创建数据库.此外,创建的数据库以后无法使用迁移进行更新.如果您的目标是关系数据库并使用迁移,则可以使用 DbContext.Database.Migrate() 方法来确保创建数据库并应用所有迁移.

Note: This method does not use migrations to create the database. In addition, the database that is created cannot later be updated using migrations. If you are targeting a relational database and using migrations, you can use the DbContext.Database.Migrate() method to ensure the database is created and all migrations are applied.

我们是如何使用 EF 6 做到这一点的?

context.Database.EnsureCreated() 等效于下面列出的 EF 6 方法:

context.Database.EnsureCreated() is equivalent to the below listed approaches of EF 6:

  1. 包管理器控制台:

  1. Package Manager Console:

Enable-Migrations -EnableAutomaticMigrations.添加迁移/更新数据库.

来自代码:

Database.SetInitializer CreateDatabaseIfNotExists

使用 DbMigrationsConfiguration 并设置 AutomaticMigrationsEnabled = true;

什么是 Database.Migrate?

将上下文的任何挂起迁移应用到数据库.如果数据库不存在,将创建该数据库.

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

我们是如何使用 EF 6 做到这一点的?

context.Database.Migrate() 等效于下面列出的 EF 6 方法:

context.Database.Migrate() is equivalent to the below listed approaches of EF 6:

  1. 包管理器控制台:

  1. Package Manager Console:

更新-数据库-TargetMigration

使用自定义 DbMigrationsConfiguration:

With a custom DbMigrationsConfiguration:

AutomaticMigrationsEnabled = false;或使用 DbMigrator.

AutomaticMigrationsEnabled = false; or with DbMigrator.

结论:

如果您使用迁移,则有 context.Database.Migrate().如果您不想要迁移并且只想要一个快速的数据库(通常用于测试),那么请使用 context.Database.EnsureCreated()/EnsureDeleted().

If you are using migrations there is context.Database.Migrate(). If you don't want migrations and just want a quick database (usually for testing) then use context.Database.EnsureCreated()/EnsureDeleted().

这篇关于如何以及在何处调用 Database.EnsureCreated 和 Database.Migrate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆