I need to add a "cascade delete" constraint to a foreign key.
The migration for creating the foreign key is the last.
CreateTable(
"dbo.DependentTable",
c => new
{
ID = c.Int(nullable: false),
SomeValue = c.Double(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.IndependentTable", t => t.IndependentTableId)
.Index(t => t.ID);
I just need to alter this line and re 'update-database'.
.ForeignKey("dbo.IndependentTable", t => t.IndependentTableId, cascadeDelete: true)
What I tried to do:
Comment code in
Down()
method to avoid losing the table and the data inside it.- roll-back to previous migration.
- alter the line.
- run
update-database
but I keep getting an error
There is already an object named 'dbo.DependentTable'
Generate New migration with
-IgnoreChanges
Call these methods:
DropForeignKey("dbo.DependentTable", "ID"); AddForeignKey("dbo.DependentTable","ID","IndependentTable",cascadeDelete: true)
Run
Update-database
That also resulted in an error
There is already an object named 'FK_dbo.DependentTable_dbo.IndependentTable_Id' in the database. Could not create constraint or index. See previous errors.
Is there a way to add cascade delete to the foreign key without losing any data?