'Entity Migration. Could not drop constraint. See previous errors
Here is the code that produce this error. I've tried solution for renaming the AddForeignKey
but the error is same.
'PK_dbo.Item' is not a constraint.
Could not drop constraint. See previous errors.
Can you suggest some solution?
public override void Up()
{
DropForeignKey("dbo.AddGallery", "item_fk_id", "dbo.Item");
DropForeignKey("dbo.ExtraFieldValue", "item_fk_id", "dbo.Item");
DropPrimaryKey("dbo.Item");
AddColumn("dbo.Item", "id", c => c.Int(nullable: false, identity: true));
AddPrimaryKey("dbo.Item", "id");
AddForeignKey("dbo.AddGallery", "item_fk_id", "dbo.Item", "id");
AddForeignKey("dbo.ExtraFieldValue", "item_fk_id", "dbo.Item", "id");
DropColumn("dbo.Item", "item_id");
}
public override void Down()
{
AddColumn("dbo.Item", "item_id", c => c.Int(nullable: false, identity: true));
DropForeignKey("dbo.ExtraFieldValue", "item_fk_id", "dbo.Item");
DropForeignKey("dbo.AddGallery", "item_fk_id", "dbo.Item");
DropPrimaryKey("dbo.Item");
DropColumn("dbo.Item", "id");
AddPrimaryKey("dbo.Item", "item_id");
AddForeignKey("dbo.ExtraFieldValue", "item_fk_id", "dbo.Item", "id");
AddForeignKey("dbo.AddGallery", "item_fk_id", "dbo.Item", "id");
}
Solution 1:[1]
I believe the primary key no longer exists and this is why it cannot be dropped.
Solution 2:[2]
I find an solution for this problem. Because I've trying to change the name of the existing primary key name, I encountered an error while migration because that primary key was referenced to other tables. So the solution was simply to add [Column("id")] DataAnnotation and than make the migration. Column name of the primary key was successfully changed without any error.
Solution 3:[3]
In my case, I used "Code first from database" approach. I had DB with my own foreign/primary key names different from ones the migration expects. So the migration just couldn't find relationships with such names. I had to explicitly name these relationships in dropping:
DropForeignKey(string dependentTable, string name);
DropPrimaryKey(string table, string name);
But be aware: using this approach, you need to explicitly modify Up and Down methods. It means, if you don't redefine Down() to match new Up method (using the previous FK/PK names) then if you go back on migrations, initial Down() will produce keys with its own names and Up() will need to have initial structure before self modifying, unless it won't find keys with such names when you use update-database again.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lajos Arpad |
Solution 2 | Olrhain |
Solution 3 | mias1 |