0

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:

  1. 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'

  2. 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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    I believe you should be able to update your OnDelete action in the Context, then add a new migration and run it. Let EF do the work of creating the migration properly. See the answer here for how to define that: https://stackoverflow.com/questions/17487577/entity-framework-ef-code-first-cascade-delete-for-one-to-zero-or-one-relations – Blaise Nov 27 '19 at 17:44
  • Honestly, Thank you so much, I don't get this part "you should be able to update your OnDelete action in the Context", but I followed the link and that helped a lot. – Abdoulrhman RIF Nov 27 '19 at 20:39

0 Answers0