Entity Framework Cascading Delete of Children in Foreign Key Relationship

Scenario

Attempt to delete an entity, which has children, from a model
  • setup database with cascading deletes.
  • go to entity framework model design in Visual Studio and “Update model from database”
  • programatically delete an entity which has children (based on foreign key relationship)

Problem
The entity’s children are not deleted, causing a foreign key constraint error and preventing the parent item from being deleted


Cause
The entity data model doesn’t, for some reason, automatically mimic the behavior of the database within its conceptual model

“If you update the database with the cascade delete rule and then update the existing model from the database, the Entity Framework will add the cascade delete rule to the SSDL but not CSDL.”
-MSDN 


Solution
Manually update the OnDelete property on the conceptual model of every Entity class that you want to support cascading deletes.  You can set the “End1 OnDelete” and/or “End2 OnDelete”.  There is a property called “End1/End2 Role Name” which you can use to determine which endpoint is which.  You will want to set the OnDelete property for the endpoint which represents the parent entity.

“You will have to add it manually. To specify the cascade delete rule in the conceptual model,
select the association on the Entity Designer surface. Then, in the Properties window, select Cascade for the OnDelete property.”

-MSDN 

 

Reference