http://weblogs.asp.net/zeeshanhirani/archive/2010/07/23/removing-entity-from-a-related-collection.aspx explains exactly what happened to you.
Assuming you have a class design something like this:
Entity Framework will generate the required foreign key columns and add NOT NULL
constraints to them because all Recipes will always be associated with exactly one ControlUnit.
So at runtime you will have objects similar to the following layout:
Now your code comes into play and deleted the relationship between the Recipe objects and their ControlUnit:
Trying to save at this moment, the database does not have a ControlUnit ID to put into the foreign key NOT NULL
column. The current object state violates the class diagram above and cannot be saved to a database layout that has been generated under the assumption that every Recipe is associated with one ControlUnit. This is why the database refuses to save the changes and you see the exception.
This also explains why it works when you uncomment the line deleting the entity: The entity is removed from the database along with its relationship, so no constraints are violated, therefore no exception.
"But I set ON DELETE CASCADE
on the relationship..."
Yes, but that is only triggered on deletion of the object, not on deletion of the relationship. With ON DELETE CASCADE
set, this should work:
controlUnitRepository.DeleteObject(_controlUnit);
// deletes the ControlUnit and all associated Recipe entities
If you want to trigger deletion of the Recipe entities on deletion of their relationship with ControlUnit, your relationship should not be a simple association but rather a composition:
EF does not support this natively, but you can emulate the behaviour using identifying relationships. Once an entity is in an identifying relationship to a parent entity and that relationship is removed, the entity is removed as well. It seems this was your intention from the start. For more information on identifying relationship, see Implementing identifying relationships with EF4 where I implemented identifying relationships with EF4 and have linked to more reading material.