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

AliRıza Adıyahşi picture AliRıza Adıyahşi · Dec 13, 2012 · Viewed 9k times · Source

DB MetersTree TABLE

id       text   parentId    state

 0       root          0     open
 1    level 1          1     open
 2    level 1          1     open
 ...     

CONTROLLER

public ActionResult GetDemoTree()
{
    OsosPlus2DbEntities entity = new OsosPlus2DbEntities();
    MetersTree meterTree = entity.MetersTree.FirstOrDefault();

    return Json(meterTree, JsonRequestBehavior.AllowGet);
}

DATA FORMAT THAT SHOULD BE (for example)

[{  
    "id": 1,  
    "text": "Node 1",  
    "state": "closed",  
    "children": [{  
        "id": 11,  
        "text": "Node 11"  
    },{  
        "id": 12,  
        "text": "Node 12"  
    }]  
},{  
    "id": 2,  
    "text": "Node 2",  
    "state": "closed"  
}]  

How can I create tree Json Data? If I write MetersTree with its relationships I get the error that is defined in the title.

Answer

Tr1stan picture Tr1stan · Dec 13, 2012

You need to break the circular reference that is being picked up because of the navigational property in your EF class.

You can map the results into an anonymous type like this, although this is untested:

public ActionResult GetDemoTree()
{
    OsosPlus2DbEntities entity = new OsosPlus2DbEntities();
    MetersTree meterTree = entity.MetersTree.FirstOrDefault();

    var result = from x in meterTree
           select new 
            {
            x.id,
            x.text,
            x.state,
            children = x.children.Select({
                c => new {
                    c.id,
                    c.text
                })
         };

    return Json(result, JsonRequestBehavior.AllowGet);
}