Cascading deletes with Entity Framework - Related entities deleted by EF
This is exactly how cascading deletes behaves in EF. Setting Cascade on a relation in EF designer instructs EF to execute DELETE
statement for each loaded realated entity. It doesn't say anything about ON CASCADE DELETE
in the database.
Setting Cascade deletion when using EF needs two steps:
- Set Cascade on relation in EF designer. This instruct context that all loaded related entities must be deleted prior to deletion of the parent entity. If this doesn't happen EF will throw exception because internal state will detect that loaded childs are not related to any existing parent entity even the relation is required. I'm not sure if this happens before execution of delete statement of the parent entity or after but there is no difference. EF doesn't reload related entities after executing modifications so it simply doesn't know about cascade deletes triggered in the database.
- Set
ON CASCADE DELETE
on relation in database. This will instruct SQL to delete all related records which were not loaded to context in the time of deleting the parent.
The implementation of cascade deletes in EF is strange and quite inefficient but this is how it behaves and if you want to use it, you must modify your application to behaves correctly in this scenario.
Instead of on the EF designer, one can also set cascade deletion on the FK Constraints in the database.
Here are the visual steps from Sql Server Management Studio (SSMS) on how to setup cascading deletes.
Note when done, don't forget to update the edmx against the database before attempting a delete.
I discuss this in more depth on my blog: Entity Framework Cascading Deletes; Set it from the database.