Circular reference detected exception while serializing object to JSON

Option 1 (recommended)

Try turning off Proxy object creation on your DbContext.

DbContext.Configuration.ProxyCreationEnabled = false;

Typically this scenario is because the application is using POCO objects (Either T4 Generated or Code-First). The problem arises when Entity Framework wants to track changes in your object which is not built into POCO objects. To resolve this, EF creates proxy objects which lack the attributes in the POCO objects, and aren’t serializable.

The reasons why I recommend this approach; using a website means that you probably don’t need change tracking (stateful) on Entity Framework objects, it free’s up memory and cpu because change tracking is disabled and it will work consistantly on all your objects the same way.

Option 2

Use a serializer (like JSON.Net which is already included in ASP.Net 4) that allows customization to serialize the object(s).

The reasons I do not recommend this approach is that eventually custom object serialization logic will be need to serial proxy objects as other objects types. This means you have a dependency on logic to deliver a result downstream. Changing the object means changing logic, and in an ASP.Net MVC project (any version) instead of only changing a View you have some thing else to change that is not readily known outside of whoever wrote the logic first.

Option 3 (Entity Framework 5.x +)

Use .AsNoTracking() which will disable the proxy objects on the specific query. If you need to use change tracking, this allows a nice intermediate solution to solution #1.

Leave a Comment