serialize entity foundation object using json.net (circular reference error)

asp.net c# entity-framework json.net

Question

I want to serialize an entity framework entity into a json object. I did some research and discovered that json.net should be able to serialize objects with circular references "out of the box" (http://james.newtonking.com/projects/json-net.aspx). I then tried using

string json = JsonConvert.SerializeObject(/* my ef entity */);

But I continue to get the same problem. I could have an issue since I need to utilizeReferenceLoopHandling.Ignore and aContractResolver I'm not sure how to utilize them, however. We much appreciate any assistance. Thanks

1
13
11/2/2011 3:59:52 PM

Accepted Answer

Simply removing the parent reference from my kid entities was my answer.

Therefore, I updated the Parent reference in my model to be Internal rather than Public after choosing the connection.

It may not be the best option for everyone, but it worked for me.

2
2/23/2012 12:06:08 PM

Popular Answer

I changed my Entities to POCO-based Code First to get around this. Right-click inside of your edmx window and choose:

Code tab > EF POCO Entity Generator > Add Code Generation Item

Keep in mind that if you don't see it, you may need to install it via nuget.

Although EF provides proxy classes to such objects at runtime for tracking reasons, they often cause problems during serialization. We can easily stop this by setting ProxyCreationEnabled to false as seen below:

var context = new YourEntities();
context.Configuration.ProxyCreationEnabled = false;

var results = context.YourEntity.Take(100).ToList();

By skipping the normal reference looping, you can then securely return JSON.NET serialized data as follows:

return JsonConvert.SerializeObject(results, Formatting.Indented, 
    new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
    });


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow