Cascade delete in Entity Framework

I hade a really hard time getting a simple cascade delete to work with the Entity Framework and i thought i had to write it down here so that i can remember it in the future.

I was trying to delete a item from my database with some childrens. But i got the error

A relationship is being added or deleted from an AssociationSet ‘FK_ItemChildren_Item’. With cardinality constraints, a corresponding ‘ItemChildren’ must also be added or deleted.

I started to google on it and i found this thread in the MSDN forums. The first suggestion where to add cascade delete to the database and then update the model to get the changes. I did that but i still got the same error. The problem where this.

The SSDL part of the edmx file where updated correctly.

<Association Name="FK_ItemChildren_Item">
 <End Role="Item" Type="Model.Store.Item" Multiplicity="1">
  <OnDelete Action="Cascade" />
 </End>
 <End Role="ItemChildren" Type="Model.Store.ItemChildren"
  Multiplicity="*" />
 <ReferentialConstraint>
 ..
 </ReferentialConstraint>
</Association>

But the CSDL part where not updated:

<Association Name="FK_ItemChildren_Item">
 <End Type="Model.Item" Role="Item" Multiplicity="1">
  <OnDelete Action="Cascade"></OnDelete>
 </End>
 <End Type="Model.ItemChildren" Role="ItemChildren"
  Multiplicity="*">
 </End>
</Association>

The line in green where not updated for some reason. When i added that in the model it worked. I guess the designer is not 100% even though the released EF.

5 Comments

  1. Todd says:

    Thanks for blogging this! You just saved me from a huge amount of frustration.

  2. Tool says:

    What an complete pain. I suppose things like this will happen since it’s relatively new but not really an excuse. Thanks for the post though. Go go entity framework.

  3. Ken Smith says:

    Yeah, and the EF isn’t even very new. This is something that should be fixed.

  4. Dario says:

    hi, thanks for the hint! it saved me a lot of frustration too!
    what a pity that this code generating part is not that reliable… but anyway, the problem is solved!

  5. Maan says:

    Hi,

    I have some problem with cascade delete in EF and I`m wondering if U could help me.

    In my application I have Customer with collection of Invoices. Each Invoice has collection of Products. I`m loading Customer objects using linq to entity query:
    var selectCustomer = from c in dbContext.Customer.Include(“Invoice.Product”)
    where c.Id == id
    select c;
    And everythig is ok, I have Customers with Invoices and its Products. But when I`m trying to delete single Customer object, EF deletes from DB only customer and invoices, but it isn`t deleting products that refer to invoice in junction table.

    Can anyone help?

Leave a Reply