Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json.net; serialize entity framework object (circular reference error)

I have an entity framework entity that i want to serialize as a json object. I looked around and found out that json.net (http://james.newtonking.com/projects/json-net.aspx) should be able to serialize objects with circular references "out of the box". So i tried using

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

But im still getting the same error. The problem might be that i need to use ReferenceLoopHandling.Ignore and a ContractResolver, but im not sure how to use them. Any help is much appreciated! Thanks

like image 377
Johan Avatar asked Nov 02 '11 15:11

Johan


2 Answers

To get around this I converted my Entities to POCO based Code First. To do this right click inside your edmx window and select:

Add code generation item > Code tab > EF POCO Entity Generator.

Note that you might need to install it with nuget if you don't see it.

At runtime however EF adds proxy classes to those objects for tracking purposes but they tend to mess up with the serialization process. To prevent this we can simply set ProxyCreationEnabled to false as follows:

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

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

You can then safely return JSON.NET serialized data by omitting the default reference looping as follows:

return JsonConvert.SerializeObject(results, Formatting.Indented, 
    new JsonSerializerSettings { 
        ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
    });
like image 94
Ziad Avatar answered Oct 24 '22 11:10

Ziad


Another solution will be adding [JsonIgnore] attribute to your navigational properties.

For example:

using System;
using System.ComponentModel.DataAnnotations.Schema;

[Serializable]
public class Entity
{
    public int EntityID { get; set; }
    public string EntityName { get; set; }

    [JsonIgnore]
    public virtual Parent Parent { get; set; }
    [JsonIgnore]
    public virtual List<Child> Children { get; set; }
}
like image 25
Kaan Yürükçü Avatar answered Oct 24 '22 09:10

Kaan Yürükçü