Entity Framework migration problem after merge

A problem with code first migrations in Entity Framework arises when migrations in two branches are merged. Although you still have all the migrations in your merged project it still says "Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration."

And if you create a new migration with the add-migration command you will end up with a migration that wants to add tables and/or fields that you already have in your database.

Even if you do an update-database -targetmigration and try to re-run the migrations the error will remain.

The cause of this problem is that each migration is created with a resource file (resx) that includes a snapshot of the database. This is what causes Entity Framework to be confused after the merge of two or more migrations.

Solving the problem

The fix is somewhat dirty but does the trick. You need to create a new migration that has the right snapshot but don't include the erroneous migrations.

  1. Add a new migration using add-migration
  2. Open the new migration and remove all the code from Up() and Down()
  3. Compile and run the project, it should be working again

This empty migration will reset the snapshot and next time you change your data model the migrations will be created correctly.

Be sure that you don't do any changes to your data model before you do this fix or otherwise make sure that you don't remove the valid migration steps.

Related posts:

Comments

comments powered by Disqus