The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

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.

I don’t quite understand this line:

The relationship could not be changed
because one or more of the foreign-key
properties is non-nullable.

Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.

The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class. This would hopefully cater for removal of child classes, addition of new ones and modifications. I would have thought Entity Framework handles this.

The lines of code can be distilled to:

var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();

21 Answers
21

Leave a Comment