
The relationship could not be changed because one or more of the foreign-key properties is non-nullable.
January 25, 2012I’ve run across this in my MVC/Entity Framework code a couple of times. Figure I better document the solution here so it is easy to find. Hat Tip to the EF 4: Removing child object from collection does not delete it – why? article on StackOverflow.
Basically, I had some child objects off of a parent that I wanted to clear off or remove before saving them fresh. When I did:
ParentObject.ChildObjects.Clear();
I was getting the following 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.
What is going on is the Clear and Remove method remove the Relationship. They don’t remove the Child Object itself…and when the relationship is removed, the Child Object looks orphaned and has a Foreign Key issue.
So what you have to do is Delete the child object from your Object Context. To avoid Enumeration errors, I make a seperate list and remove it that way.
List<ChildObject> children = ParentObject.ChildObjects.ToList();
for (int i = 0; i < children.Count; i++)
{
try
{
//Delete the Child Object from your ObjectContext
//(We have a wrapper function to do that
dataAccessor.Delete(children[i]);
}
catch
{
}
}