Circular reference error when outputting LINQ to SQL entities with relationships as JSON in an ASP.N
- by roosteronacid
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.