Wednesday, August 7, 2013

Entity Framework Constraint Woes

This morning I was working on updating a few models in an ASP.NET MVC4 app and then needed to update the database with these changes when I was presented with an error that threw me for a little loop. In my Entity Framework migration scaffold the code looked like:

DropPrimaryKey("dbo.{{TableName}}", new[] { "Id" });

This code resulted in the following error:

'PK_dbo.{{ModelName}}' is not a constraint.
Could not drop constraint. See previous errors.



As I was expecting that Entity Framework has set up the migration with the constraint name being 'PK_dbo.{{ModelName}}' it took me a few moments to check the constraint name in SQL server to find that the naming of that constraint was an older naming from previous model updates that had not been renamed by EF.

Luckily this is an easy fix. The DropPrimaryKey() method has an overload that allows you to specify the name on the constraint and viola! problem solved!

DropPrimaryKey("dbo.{{TableName}}", "PK_dbo.{{KEYNAME}}", new[] { "Id" });

Happy coding!

No comments:

Post a Comment