How did I solve the Json serializing circular reference error? How did I solve the Json serializing circular reference error? json json

How did I solve the Json serializing circular reference error?


If you turn off proxy creation you also turn off lazy loading. When serialization of entity occures it visits all navigation properties. If lazy loading is enabled it loads all related objects and tries to serialize them as well. Again it visits all their properties including navigation properties pointing back to parent object. At this point you have to say serialization that this property is circular reference or it will serialize the object again and continue in infinite loop.

The trick here could be to annotate your circular navigation property in child entity with the ScriptIgnore attribute.


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 ;-)


Quick note: if you still face the exception remember getting rid of

.Include("NestedObject")

This way parent-child relationship will be gone as well as the exception