As I understand, if I delete a parent row, its children should be deleted if I turn on cascade on delete. However, from my testing, it doesn't seem to work at all. No matter if I set WillCascaseOnDelete to true or false, it simply sets the foreign key of its children to null. This is causing another problem that I have to set the foreign key nullable, otherwise, SaveChange will throw exception. Is this a defect or desired behavior?
Asked
Active
Viewed 2.9k times
2 Answers
15
This is because your foreign keys (child) are nullable. By default, when deleting parent, if the foreign key on the relationship is nullable EF will delete the parent and set the foreign key to null. If the foreign key is NOT NULL it will delete the child (the behaviour you're looking for?).
You can alter this default behaviour here

Matt Cotton
- 732
- 9
- 23
-
3I'm experiencing same problem, my Foreign Key is set as `IsRequired();`, the relationship has `.WillCascadeOnDelete(true)` but I still get an Exception when trying to delete the parent object. – Steven Ryssaert Jul 19 '14 at 09:02
-
@UwConcept, I would expect an exception to be thrown if you've specified the foreign-key relationship as `IsRequired();` as Entity Framework cannot set the value to `null` following removal of the parent object. – weenoid Oct 05 '15 at 10:42
-
3@weenoid Thanks for your reply. But wouldn't it make more sense to then delete the child object instead of setting a NULL value in a non nullable field? Just my two cents. – Steven Ryssaert Oct 06 '15 at 09:01
-
1@StevenRyssaert Entity framework will delete such objects. Just make sure that those are loaded into the context via Include or LazyLoading. EntityFramework cannot mark object as deleted if it doesn't know that this object exists – Machet Sep 23 '18 at 15:20
2
Make sure on the Foreign Key Relationship window in SQL Server, you have selected Cascade as Delete rule.

asr
- 716
- 5
- 9