Circular reference with Entity Framework and Json when developing with Asp.Net MVC<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Circular reference with Entity Framework and Json when developing with Asp.Net MVC

Posted on: October 29, 2012

A circular reference was detected while serializing an object of type.

Here come the problem of serializing. First of all, this occur because a parent object reference a child object and this one reference back to its parents. Sound familiar? Well, if you are working with Entity Framework and Code First, it should. Why? Because most of the Entity are cross referencing each others. This way, it's convenient for many operations. For example, if you are a Team entity that has a list of Player, won't it be convenient to have the User having a Team property to access his team name. It's also interesting to do myPlayer.Team.Id = 1 and save the myPlayer. This way you do not have to instantiate the Team 1 object and add the player and save the team. Anyways, that's how Entity Framework work and when it's time to serialize to Json, it can cause this behavior.

The second problem is concerning the object itself. When trying to serialize, you are in fact serializing the Proxy also which is not what you want. In fact, you will get this error.

The RelationshipManager object could not be serialized. This type of object cannot be serialized when the RelationshipManager belongs to an entity object that does not implement IEntityWithRelationships.

This is why you should disable the proxy creation and handle the state of your poco with the DbContext instead of relying on proxy. Disabling the proxy is a matter of setting to false your DbContext's property ProxyCreationEnabled.

1_dbContext.Configuration.ProxyCreationEnabled = false;

Let's come back to the main purpose of this article. The problem with circular reference can be fixed by two solutions.

The first one, is to broke those references when we send the information to Json. That mean that in your controller, before sending back the ActionResult, you loop problematic property to remove the reference. If we take back the example with Player and Team, we could simply loop the Team array of Player and set to Null all Player[i].Team.

The second solution can be to use the attribute ScriptIgnore over the property of Team for example. So, it will serialize only from one side. I haven't try this solution that I have found at because I do not think that I should alter the Model for the View this way. The serialization process shouldn't impact the model and for sure not to make something work only in half. At the end, we loss the reference on one side which will require to us to rebind it later on.

A better solution is to use a different library of Json which can handle reference, by that I mean the Newton King Library. This library support circular reference by add ID to object serialized.

First, you need to remove the serialization from the default Json serializer and use the Json Newton King Library. This can be done in the Global.asax.cs file. with the following code.

2GlobalConfiguration.Configuration.Formatters.Add(new JsonNetFormatter(new JsonSerializerSettings()));
4var jsonSerializerSettings = new JsonSerializerSettings {
5 PreserveReferencesHandling = PreserveReferencesHandling.Objects

As you can see, we are setting up the PreserceReferencesHandling.Ojects. This will add the reference to object when circular dependencies are found.

This setting add values into the Json structure that in the format "$id": "1" and instead of copying the object over and over (and creating a stack over flow), will use the syntax "$ref": "1" to refer to the object. For example, if we have an object Player that contain the Team and the Team contains the players, than we could have circular reference. The serialization with the library and the PreserceReferencesHandling will produce something similar to the code below if we serialize a single player.

The C# code:

1class Program {
2 static void Main(string[] args) {
3 var p = new Program();
4 }
6 public Program() {
7 var t1 = new Team() {
8 TeamName = "MyTeam"
9 };
10 var p1 = new Player {
11 PlayerName = "Patrick" ,PlayerTeam = t1
12 };
13 var p2 = new Player() {
14 PlayerName = "Melodie" , PlayerTeam = t1
15 }; t1.Players.Add(p1);
17 t1.Players.Add(p2);
19 var settings = new JsonSerializerSettings() {
20 PreserveReferencesHandling = PreserveReferencesHandling.Objects
21 };
22 string json = JsonConvert.SerializeObject(p1, settings);
23 Console.WriteLine(json);
24 Console.ReadLine();
25 //Product deserializedProduct = JsonConvert.DeserializeObject<Player>(json);
27 }
30public class Player {
31 public string PlayerName { get; set; }
32 public Team PlayerTeam { get; set; }
35public class Team {
36 public string TeamName { get; set; }
37 public List<Player> Players { get; set; }
38 public Team() {
39 this.Players = new List<Player>(); }
40 }
42The result:
46 "$id":"1",
47 "PlayerName":"Patrick",
48 "PlayerTeam": {
49 "$id":"2",
50 "TeamName":"MyTeam",
51 "Players": [
52 { "$ref":"1" },
53 { "$id":"3",
54 "PlayerName":"Melodie",
55 "PlayerTeam": { "$ref":"2" } }
56 ]
57 }

If instead your serialize the team you will get:

2 "$id":"1",
3 "TeamName":"MyTeam",
4 "Players": [
5 {"$id":"2","PlayerName":"Patrick","PlayerTeam":{"$ref":"1"}},
6 {"$id":"3","PlayerName":"Melodie","PlayerTeam":{"$ref":"1"}}
7 ]

To conclude, you have to remember two things with Asp.Net MVC and Entity Framework. First, if you have not disabled proxy, than you will have this object serialized and it will cause problem when serializing. Second, you need to break those circular reference to stop the possibility of stack overflow. Using Json Newton library is simple and powerful when it came to handling references.