为什么Add-Migration有时会创建重复迁移? [英] Why does Add-Migration sometimes create duplicate migrations?

查看:1027
本文介绍了为什么Add-Migration有时会创建重复迁移?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的一个奇怪的问题与代码第一次迁移在Entity框架版本5.有时更新数据库失败,由于暂挂的更改,但 Migration 命令仅生成迁移,其中数据库更改已包含在上次迁移中,并且数据库是最新的。因此,我希望新的迁移为空。

I am facing a weird problem with code first migrations in Entity Framework version 5. Sometimes Update-Database fails due to pending changes but Add-Migration command only produces migrations with database changes already contained in the last migrations and the database is up-to-date. Therefore I'd expect the new migration to be empty.

如何添加迁移 ?它似乎不使用数据库作为源。

How does Add-Migration detect what changes are due? It doesn't seem to use the database as a source.

推荐答案

数据库模型的快照随每次迁移一起保存在.resx文件中。添加新迁移时,EF将当前数据库模型(从您的模型类和DbModelBuilder的设置生成)与上次迁移进行比较,并确定它们之间的更改。

A snapshot of the database model is saved along with every migration in a .resx file. When you add a new migration, EF compares the current database model (which is generated from your model classes and settings from your DbModelBuilder) with the last migration and determines a changes between them.

如果您的迁移不同步,可能会出现您所描述的问题。如果两个开发人员进行两个独立的迁移,这些迁移将被合并回默认分支。发生在我们身上。

The problem you are describing can occur if your migrations are out of sync. It happens to us if two developers make two independent migrations and these migrations are later merged back to the default branch.

示例:


开发人员1

迁移AddColumnA

Migration AddColumnA

开发人员2

迁移AddColumnB

Migration AddColumnB

合并版本

迁移AddColumnA - 数据库快照包括columnA

Migration AddColumnA - database snapshot includes columnA

迁移AddColumnB - 数据库快照包括columnB, b $ b columnA

Migration AddColumnB - database snapshot includes columnB but not columnA

如果添加其他迁移,则根据不包含columnA信息的迁移AddColumnB确定更改。此问题的解决方法是生成虚拟迁移(使用空Up和Down方法),以便在上次迁移时具有正确的数据库模型快照。

If you add another migration, the changes are determined against migration AddColumnB, that doesn't contain information about columnA. A workaround for this problem is to generate dummy migration (with empty Up and Down methods) just to have the correct database model snapshot in the last migration.


合并的版本

迁移AddColumnA - 数据库快照包括columnA

Migration AddColumnA - database snapshot includes columnA

迁移AddColumnB - 数据库快照包含columnB,但不包含
columnA

Migration AddColumnB - database snapshot includes columnB but not columnA

迁移虚拟 - 包含columnA和columnB的数据库快照

Migration Dummy - database snapshot with columnA and columnB

这篇关于为什么Add-Migration有时会创建重复迁移?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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