Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4: Removing child object from collection does not delete it - why?

I use Entity Framework 4 and I have parent - child relation with "Cascade Delete" set. So i would expect when i remove a child from the parent that the child is deleted when i call SaveChanges().

        cuRepository.Attach(_controlUnit);         foreach (var recipe in recipes) {             _controlUnit.Recipes.Remove(recipe);             //repository.DeleteObject(recipe);         } 

Instead i get an error:

System.InvalidOperationException occurred Message=The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

When I explicitly delete the children (see commented line), all is fine. What am I missing?

like image 740
H. Kocher Avatar asked Mar 31 '10 16:03

H. Kocher


People also ask

How do I delete EF records?

Delete a Record In Connected Scenario, you can use the Remove or RemoveRange method to mark the record as Deleted . In Disconnected Scenario, you can attach it to the context and set its state as Deleted . Calling SaveChanges will send the delete query to the database.


1 Answers

You aren't deleting the object with the remove statement. Instead you are attempting to alter a record and make it an orphan (by setting the foreign key to null). The database has a non-null constraint on that column and prevents you from doing so.

like image 99
Amy B Avatar answered Oct 11 '22 07:10

Amy B