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

查看:339
本文介绍了如何以及在何处调用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. Package Manager控制台:

  1. Package Manager Console:

启用迁移-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. Package Manager控制台:

  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天全站免登陆