Merging migration entries in Entity Framework

2019-04-22 14:10发布

问题:

I have an Entity Framework 6 CF project that has a few migrations already in place.

The model is now stable and there is no need to keep the migration history that already exists.

Is there a way to reset the model and merge all migration commands into the initial migration?

As an example, the first migration adds a column while the second migration adds a unique, non-clustered index. I now want to see all these changes directly in OnModelCreating rather than in separate migrations.

回答1:

Migrations have both an Up and Down. You can always Re-Scaffold your application by tearing the migrations down and then adding a new migration. The Down process does not change your model, only the changes to the database. Use Update-Database -Target:migrationTargetName or Update-Database -TargetMigration:migrationNumber.

If you want a migration which starts with no database and ends with your current model, you can tear all the migrations down with Update-Database -TargetMigration:0. It's a good idea to tear down the database and then run Update-Database as a test to verify the database changes are all in sync.

Bear in mind, if you tear your migrations down to 0 and then run an Add-Migration, you will want to look very closely at the generated scaffold, as it will likely be drastically different than the incremental changes.