Home » Ado.Net » Entity Framework » Entity Framework Uniqueness of Complex Object reference

Entity Framework Uniqueness of Complex Object reference

Working with Entity Framework and Complex object can be challenging. For example, they must be defined even if in your code you set them as null. Another limitation of complex object is that you cannot have two of them referencing the same object. You will get the following error when saving:

The entity of type ‘xxx’ references the same complex object of type ‘zzz’ more than once. Complex objects cannot be referenced multiple times by the same entity.

This can happen really easily. Imagine this scenario where you have an entity that has two properties of a complex type “Money”.

public class House{
    public Money CurrentPrice{get;set;}
    public Money BoughtPrice{get;set;}

If you just buy the house, the current price and bought price will be the same. You may just set the same Money instance to both properties. However, it will fail. It fails not because they have the same inner value (let’s say the same decimal) but fails because both properties are linked to the same complex object.

The quick fix is to clone the price before saving the entity. By cloning each properties, they will be of the same complex type, but both objects will have be from a different object. Since complex type is simple by nature, like cannot reference other entities, the cloning is usually very simple if not just using the basic MemberwiseClone.

This is one of many traps that you may figure out only once you hit the database with the specific code of having the same reference. Do not overlook that scenario and always make sure that complex objects come with a unique instance before saving your changes with Entity Framework.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon.

Leave a Reply

Your email address will not be published. Required fields are marked *