Resetting Entity Framework 5 code first migrations

Working with a messed up DB that had been manually modified while using Entity Framework 5 code first approach is not fun. Not only that, but the migrations had been deleted from the project and from the Migrations History table AND the production database and staging database had not been updated so it was out of sync. What to do while retaining the data?

1. Make a complete backup of your product database and copy it to your dev environment.
2. Restore production db in dev under a new name
3. Compare the dev and production db to note the differences (Redgate can help)
4. Change the web.config and connection strings to point to the new production duplicated db in your dev environment
[ Using the new production db copy in your dev environment]
4. Enable Entity Migrations (if necessary)
5. Run an Add-Migrations – the code generated will re-add all of the tables. Comment out all of the tables that you already have in both the up and down
6. Using the differences found in step 3, manually add code that adds the missing database fields. You shouldn’t need to add complete tables as you can leave those uncommented from those generated in step 5
7. Run update-database
8. Run your app (again pointing to the new production db copy that was just updated) and ensure everything works
9. Push to staging/qa/production as you follow your standard release processes and everything should work!

Posted in Uncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *