使EF4.3代码优先迁移忽略挂起的迁移 [英] Make EF4.3 Code First Migrations ignore pending migrations
问题描述
我有一个最近使用 DbContext.Database.Create()
创建的数据库的本地实例,所以 __ MigrationHistory
表存在与当前代码匹配的 InitalCreate
条目。
I have a local instance of a database that I recently created using DbContext.Database.Create()
, so the __MigrationHistory
table exists with an InitalCreate
entry that matches the code at the moment.
但是,迁移文件夹中存在一些基于代码的迁移。这些将在我们的开发和登台环境中运行,以使这些数据库与代码保持一致。但是,由于我使用当前代码创建了数据库,因此不需要在本地应用它们。
Some code-based migrations exist in the Migrations folder, however. These will be run in our development and staging environments to bring those databases in line with the code. I don't need to apply them locally, however, since I created the database using the current code.
我现在需要对模型进行更改并创建相应的迁移。但是当我运行 Add-Migration TestMigration
时,出现以下错误
I now need to make a change to the model and create the corresponding migration. But when I run Add-Migration TestMigration
, I get the following error
Unable to generate an explicit migration because the following explicit
migrations are pending:
[201203271113060_AddTableX,
201203290856574_AlterColumnY]
Apply the pending explicit migrations before attempting to generate
a new explicit migration.
在这种情况下我该怎么办?我无法将添加迁移工具指向另一个环境,因为它不能保证该版本与我在本地拥有的版本匹配。我希望迁移仅与我所做的更改匹配。
What should I do in this case? I can't point the Add-Migration tool at another environment because it's not guaranteed that version matches what I have locally. I want a migration that matches only the changes I've made.
似乎我有一些选择,但都不是理想选择:
It seems I have a few options but none are ideal:
- 从迁移文件夹中删除其他迁移,运行添加迁移命令,升级数据库,然后还原旧的迁移。这很简单,但似乎有点怪异。
- 在源代码管理中恢复模型的版本,该模型是第一次迁移所应用于的版本,然后进行构建并使用它来创建数据库。然后获取最新版本,应用所有迁移,然后准备添加迁移。
- 手动创建迁移。
有人吗?有关如何管理此问题的任何建议?
Does anyone have any suggestions about how to manage this?
推荐答案
我发现最有效的方法很简单:不要使用 DbContext.Database.Create()
启用迁移后。如果要以编程方式创建新数据库,请改用Migrations API。
What I've found works best is very simple: don't use DbContext.Database.Create()
once you've enabled migrations. If you want to programmatically create a new database, use the migrations API instead.
var migrator = new DbMigrator(new Configuration());
migrator.Update();
然后,您便拥有了完整的迁移历史记录,并且可以按预期的方式添加更多迁移。
Then you've got the full migration history and adding further migrations works just as expected.
这篇关于使EF4.3代码优先迁移忽略挂起的迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!