Sharing my thoughts on software development

Tuesday, September 17, 2013

Entity Framework Code First Migration Merge Conflicts

One of the major headaches with Entity Framework 5 Code First is merging migrations. Basically, if two developers works on their local branches independently, and both created a migration, merging can be quite a pain. 

The reason is that each migration keeps migration history in its .resx file, and when two migrations are created independently based on the same base migration, EF will only recognize one of the migrations (normally your local one) and go haywire.

In order to resolve this problem, you must manually re-generate your local migrations so they are based on latest migrations from other branches you are merging from, maintaining a single line of history, similar to git rebase.

Here is the step-by-step guide:

  1. Before Merge, take note of the migration you added (MyMigration), and its previous migration (BaseMigration)
  2. Merge branches in git
  3. Open Package Manager Console, and run: UPDATE-DATABASE -TargetMigration:BaseMigration. This will revert your database to the state before any of the conflicted migrations are applied
  4. Delete your local migration (MyMigration)
  5. Run: UPDATE-DATABASE. This will apply all newer migrations done in other branches.
  6. Run: ADD-MIGRATION MyMigration. This will add your local migration based on the other branches' migrations, like git -rebase.
  7. Run: UPDATE-DATABASE. Update database with you local migration.
This also works if you have multiple local migrations, but it will merge them all into a single one.

No comments:

Post a Comment