cllpse
cllpse

Reputation: 21727

Circular reference error when outputting LINQ to SQL entities with relationships as JSON in an ASP.NET MVC 2 Web Application

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.

Upvotes: 4

Views: 1963

Answers (3)

kuma  DK
kuma DK

Reputation: 1861

Its because it is trying to load child objects and it may be creating some circular loop that will never ending( a=>b, b=>c, c=>d, d=>a)

you can turn it off only for that particular moment as following.So dbcontext will not load customers child objects unless Include method is called on your object

use something similar to this..

  db.Configuration.ProxyCreationEnabled = false;
  User ma = db.user.First(x => x.u_id == id);
  return Json(ma, JsonRequestBehavior.AllowGet);

Upvotes: 0

secretformula
secretformula

Reputation: 6432

This a late answer but you could always convert from the LINQ class to an anoynmous type that includes the properties that you want in JSON. i.e

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

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062790

In most cases involving serialization problems, the simplest thing to do is to translate the data into a simple DTO model that models exactly what you want (and not the bits you don't). So have an MyDtos.Ingredient class that looks like your Whatever.Ingredient class, but which doesn't have the relationship you don't want. LINQ is good at that:

var mapped = from i in ingredients
             select new MyDtos.Ingredient {
                Id = i.Id, Name = i.Name, ...
             };

You could also look at AutoMapper or implicit conversion operators to do the same without having to write too much extra mapping code each time.

Upvotes: 4

Related Questions