将EF迁移整合到新的InitialCreate中 [英] Consolidating EF migrations into new InitialCreate
问题描述
我已经使用EF迁移已有一段时间了,并且我的项目中有100多个迁移文件。在进行下一步之前,我想将它们合并为一个迁移-即,我想用一个考虑了所有后续更改的新版本替换现有的InitialCreate迁移,以便随后删除所有其他迁移文件。
I have been using EF migrations for some time now and have more than 100 migration files in my project. I would like to consolidate these into a single migration before moving forward - ie I want to replace the existing InitialCreate migration with a new version that takes all my subsequent changes into account so I can then delete all the other migration files.
如果我不担心丢失数据库中的所有数据,我会很容易地做到这一点,但是我确实如此。
I do this very easily if I am not concerned with losing all the data in the DB, but I am.
如何我可以做到这一点,同时保持所有数据完整无缺,还可以通过仅运行Update-Database(我相信使用朱莉·勒曼(Julie Lerman)概述的方法)?
How can I achieve this whilst keeping all data intact and also retaining the ability to recreate the database from scratch (without data) by just running Update-Database (which I believe is not possible using the approach outlined by Julie Lerman)?
推荐答案
请考虑阅读Rick Strahl的这篇不错的文章:
https:// weblo g.west-wind.com/posts/2016/jan/13/reset-entity-framework-migrations-a-clean-slate
Consider reading this nice article from Rick Strahl : https://weblog.west-wind.com/posts/2016/jan/13/resetting-entity-framework-migrations-to-a-clean-slate
基本上,该解决方案不是简单的,它不仅需要将所有迁移重置为一个
,还需要更多,因为您有两种情况需要适合一个迁移类:
Basically the solution is not trivial and needs more than just reseting all the migrations into one because you have two scenarios that needs to fit in ONE migration class:
- 创建一个新数据库=>迁移类应该包含每个表的创建
- 我的数据库已经是最新的=>我需要一个空的迁移类
解决方案:
该过程的想法基本上是这样的:数据库和EF模式是最新的,并且与您想要它,所以我们将删除现有的迁移并创建一个新的初始迁移。
Solution: The idea of this process is basically this: The database and the EF schema are up to date and just the way you want it, so we are going to remove the existing migrations and create a new initial migration.
总而言之,执行此操作的步骤是:
In summary, the steps to do this are:
- 从数据库中删除_MigrationHistory表
- 删除项目的Migrations文件夹中的各个迁移文件
- 在Packa中启用迁移ge Manager控制台
- 在PMC中添加初始迁移
- 在初始迁移中注释掉Up方法内部的代码
- PMC中的更新数据库(除了创建迁移
条目外什么都不做)在Initial方法中删除注释您现在基本上已经将
的架构重置为最新版本。 - 注释注释完的迁移已在所需数据库上执行后,取消注释迁移代码
- Remove the _MigrationHistory table from the Database
- Remove the individual migration files in your project's Migrations folder
- Enable-Migrations in Package Manager Console
- Add-migration Initial in PMC
- Comment out the code inside of the Up method in the Initial Migration
- Update-database in PMC (does nothing but creates Migration Entry) Remove comments in the Initial method You've now essentially reset the schema to the latest version.
- once the commented out migration has been executed on the desired database, uncomment the migration code
这篇关于将EF迁移整合到新的InitialCreate中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!