Circular reference detected exception while serializing object to JSON Circular reference detected exception while serializing object to JSON json json

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.


Your POCO entities are perfectly serializable. Your problem is that the dynamic proxies the EF runtime creates for you are usually not. You can set the context.Configuration.ProxyCreationEnabled to false but then you lose lazy loading. My strong recommendation to you is to use Json.NET which supports serialization for EF entities:

ADO.NET Entity Framework support accidently added to Json.NET

Popular high-performance JSON framework for .NET


I spent countless hours attempting all of the various solutions I found scattered throughout the web, including:

  • [JsonIgnore]
  • Internal Getters
  • Disabling LazyLoadingEnabled and ProxyCreationEnabled
  • Setting ReferenceLoopHandling to "ignore"
  • Carefully using explicit loading where needed

All of which ultimately proved fruitless for me. Ignoring a property helped one query, but hurt 3 others. It felt like the programming equivalent to whack-a-mole.

The context of my problem was that the data going in an out of my application had to be JSON. No way around it. Inserts and updates obviously pose much less of a problem. But selecting data that's stored in a normalized database (and in my case including a version history) to be serialized is a nightmare.

The solution:

Return the data (properties) you need as anonymous objects.

A code example:

In this case I needed the 3 latest tickets, based on "Date Scheduled". But also needed several properties stored in related entities.

var tickets =     context.TicketDetails    .Where(t => t.DateScheduled >= DateTime.Now)    .OrderBy(t => t.DateScheduled)    .Take(3)    .Include(t => t.Ticket)    .Include(t => t.Ticket.Feature)    .Include(t => t.Ticket.Feature.Property)    .AsEnumerable()    .Select(        t =>        new {            ID = t.Ticket.ID,            Address = t.Ticket.Feature.Property.Address,            Subject = t.Ticket.Subject,            DateScheduled = String.Format("{0:MMMM dd, yyyy}", t.DateScheduled)    });

And voila, no self referencing loops.

I realize this situation may not be adequate in all cases given that entities and objects may change. But it's certainly worth some consideration if all else fails.