Friday, July 18, 2014

Unable to determine principal end of relationship error in EF

Occasionally, you may get the following error:
Unable to determine the principal end of the 'Model.FK_Parent_Child' relationship. Multiple added entities may have the same primary key.
This is generally caused by attempting to use a primary key property before it has been initialized.  For example.  Let say that you have created the parent and child records, but have not saved either to the database yet.  If the primary key on the parent is an identity field (let's call it 'ParentId', this means that the value has not been initialized.

So if you attempt to link the child to this parent by using this id, you will get the error above:
Child.ParentId = Parent.ParentId
Instead, you want to use the navigation properties to link these records.
Child.Parent = Parent

1 comment:

  1. It proved to be Very helpful to me and I am sure to all the commentators here!