EF核心迁移 [英] EF Core Migrations

查看:166
本文介绍了EF核心迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对现有数据库使用迁移并创建一个新数据库(如果不存在)。

I am trying to use migrations with a existing database and to create a new one, if not exists.

EF Core文档说:

The EF Core documentations says:


如果在数据库已经存在时创建了初始迁移,则会生成数据库创建代码,但是由于数据库已经与数据匹配而不必运行它模型。当您将应用程序部署到尚不存在数据库的另一个环境时,此代码将运行以创建您的数据库

If you created the initial migration when the database already exists, the database creation code is generated but it doesn't have to run because the database already matches the data model. When you deploy the app to another environment where the database doesn't exist yet, this code will run to create your database

来自EFCore文档

我进行了初始迁移,它创建了创建表的上下方法。当我将其运行到新数据库(连接字符串中的新数据库名称)时,它将按预期创建数据库和表。

I did initial migrations, it creates a up and down methods to create my tables. When I run it to a new database (new database name in connection string) it creates the database and tables as expected.

但是如果我将其运行到现有数据库( (不是由迁移创建的),它在尝试创建已经存在的表的第一种方法失败,并且迁移停止运行。

But if I run it to an existing database (not created by migrations), it fails at the first up method that tries to create a table that already exists, and the migrations stops to run.

Docs说 不必运行,但是迁移要做的第一件事就是尝试创建现有表。

Docs says "it doesn't have to run", but first thing migrations is doing is try to create an existing table.

如何防止迁移尝试创建现有表?迁移中是否内置了类似如果不存在则创建的内容?文档正确吗?

How to prevent migrations to try to create existing tables? There is something like "create if not exists" built in on migrations? Is documentations right? It should works as expected/describe in docs?

如果我做错了,与现有数据库和新数据库一起运行的迁移策略是什么?

If I'm doing it wrong, what is the strategy to work with migrations to run with existing and new on databases?

Dotnet Core版本:1.1。
EFCore版本:1.1.2。

Dotnet Core version: 1.1. EFCore version: 1.1.2.

预先感谢。

推荐答案

您需要对现有数据库进行基准迁移。在EF 6中,您使用了 -IgnoreChanges 标志,但是Core目前不存在该标志。请参见此处

You need a baseline migration for the existing database. In EF 6 you used the -IgnoreChanges flag, but that doesn't exist in Core right now. See here.

通过注释掉所有Up()代码并应用该迁移,您可以在EF Core中完成相同的操作。这将创建__MigrationHistory表并插入一条记录,表明该表已被应用。

You can accomplish the same thing in EF Core by commenting out all the Up() code and applying that migration. This will create the __MigrationHistory table and insert a record denoting it has been applied.

随后的迁移将同时应用于这两者,并且如果需要创建一个新的数据库,您将被覆盖

Subsequent migrations will be applied to both and if you need to create a new database you are covered.

这篇关于EF核心迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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