Circular reference error when outputting LINQ to SQL entities with relationships as JSON in an ASP.N

Posted by roosteronacid on Stack Overflow See other posts from Stack Overflow or by roosteronacid
Published on 2010-04-12T12:13:02Z Indexed on 2010/04/12 12:23 UTC
Read the original article Hit count: 655

Filed under:
|
|
|

Here's a design-view screenshot of my dbml-file.

The relationships are auto-generated by foreign keys on the tables.

When I try to serialize a query-result into JSON I get a circular reference error..:

public ActionResult Index()
{
    return Json(new DataContext().Ingredients.Select(i => i));
}


But if I create my own collection of "bare" Ingredient objects, everything works fine..:

public ActionResult Index()
{
    return Json(new Entities.Ingredient[]
    {
        new Entities.Ingredient(),
        new Entities.Ingredient(),
        new Entities.Ingredient()
    });
}

... Also; serialization works fine if I remove the relationships on my tables.


How can I serialize objects with relationships, without having to turn to a 3rd-party library?

I am perfectly fine with just serializing the "top-level" objects of a given collection.. That is; without the relationships being serialized as well.

© Stack Overflow or respective owner

Related posts about c#

Related posts about mvc