Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does WillCascadeOnDelete in Entity Framework work?

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?

like image 588
newman Avatar asked Jul 29 '13 19:07

newman


People also ask

What is WillCascadeOnDelete?

WillCascadeOnDelete() Configures cascade delete to be on for the relationship. WillCascadeOnDelete(Boolean) Configures whether or not cascade delete is on for the relationship.

How to set cascade delete in Entity Framework?

For Database to delete the related entities we need to set up the Referential actions like FOR DELETE CASCADE or FOR DELETE SET NULL when we set up the ForeignKey. For Example, consider the following query where we are deleting the department with id 3. It will have no effect on Employee Records as they are not loaded.

How to disable cascade delete in Entity Framework core?

There are two ways to handle this situation: Change one or more of the relationships to not cascade delete. Configure the database without one or more of these cascade deletes, then ensure all dependent entities are loaded so that EF Core can perform the cascading behavior.


1 Answers

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

like image 121
Matt Cotton Avatar answered Sep 23 '22 02:09

Matt Cotton