Showing posts with label Code First Migration. Show all posts
Showing posts with label Code First Migration. Show all posts

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

Wednesday, 18 December 2013

ASP.NET MVC 4 Entity Framework (EF) Code First

I'm finding this a very fast and efficient way of creating .NET MVC Web Applications but still find I have to keep looking up the initial stages of setting up Entity Framework Migrations. With that in mind I'll be updating this post periodically with summary notes on what's involved.

The best article I've found on this subject so far is on dominikgorecki.com entitled "Code First Entity Framework with MVC4 and Visual Studio 2012".