The circular reference happens because you use eager loading on the object.
You have a couple of methods:
- Turn off eager loading when your loading your Query (linq or lambda)
DbContext.Configuration.ProxyCreationEnabled = false;
- Remove the virtual keyword from the Domainmodel
- Include them while loading the objects
- Detach the objects (= no eager loading functionality & no proxy)
- Repository.Detach(entityObject)
- DbContext.Entry(entityObject).EntityState = EntityState.Detached
- Clone the properties
- You could use something like AutoMapper to clone the object, don't use the ICloneable interface, because it also clones the ProxyProperties in the object, so that won't work.
- In case you are building an API, try using a separte project with a different configuration (that doesn't return proxies)
PS. Proxies is the object that's created by EF when you load it from the Entity Framework. In short: It means that it holds the original values and updated values so they can be updated later. It handles other things to ;-)