Cyclic link error when outputting LINQ to SQL objects with relations as JSON in ASP.NET MVC 2 web application

Here is a screenshot of my design dbml file.

Relations are automatically generated by the foreign keys of the tables.

When I try to serialize the result query in 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 Ingredient bare 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 delete relationships on my tables.


How can I serialize objects with links without accessing a third-party library?

I can only do fine with serializing the top-level objects of this collection. without serializing relationships.

+4
source share
3 answers

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

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

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

+4
source

This is a late answer, but you can always convert from a LINQ class to an anonymous type that includes the properties 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 })); } 
+2
source

This is because it tries to load child objects and can create some kind of cyclic loop that will never end (a => b, b => c, c => d, d => a)

You can disable it only at that particular moment, as indicated below. So dbcontext will not load child objects of clients if the Include method is called on your object

use something like this.

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

Source: https://habr.com/ru/post/1306690/


All Articles