EF 核心迁移 [英] EF Core Migrations

查看:36
本文介绍了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文档

我做了初始迁移,它创建了一个 up 和 down 方法来创建我的表.当我将它运行到新数据库(连接字符串中的新数据库名称)时,它会按预期创建数据库和表.

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.

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

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 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 核心版本: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.

您可以在 EF Core 中通过注释掉所有 Up() 代码并应用该迁移来完成相同的事情.这将创建 __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天全站免登陆