Thursday 27 November 2014

Entity Framework 5 Code First - Customizing Migrations

You want to make changes to your Models and Database, you have auto migration enabled and you run:

update-database -force

you get this error:

'FK_dbo.{TABLENAME}_dbo.{OTHER_TABLENAME}_otherID' is not a constraint.
Could not drop constraint. See previous errors.

You sh*t a brick.

Solution:

Run this:

Add-Migration Update{You Model Name}Class

This creates a file in Migrations containing a Partial Class outlining what changes the Framework is attempting as a "best guess"

Remove any unwanted changes in this file.

E.g DropForeignKey("dbo.{TABLENAME}", "otherID", "dbo.{OTHER TABLE}");

Now run:

Update-Database –TargetMigration:Update{You Model Name}Class

NOW READ THIS, TWICE!

http://msdn.microsoft.com/en-gb/data/jj591621.aspx#customizing

And if none of that works

If you're still getting errors, and trust me, it happens. Then I recommend backing everything up and starting with a clean slate.

I followed the instructions here http://stackoverflow.com/questions/11679385/reset-entity-framework-migrations from Todd. Thank's Todd :)

  1. Delete the migrations folder in your project
  2. Delete the __MigrationHistory table in your database (may be under system tables)
  3. In PM Console run: Enable-Migrations -EnableAutomaticMigrations -Force
  4. In PM Console run: Add-Migration Initial
  5. In PM Console run: update-databse -TargetMigration:Initial