Entity to json error - A circular reference was detected while serializing an object of type

.net asp.net-mvc-4 c# entity-framework json

Question

Following error occurred when trying to convert entity object into JSON String. I'm using C# MVC4 with code first DB designing. It seams its because FKs and relationships between tables create this issue. What will be the workaround ?

A circular reference was detected while serializing an object of type System.Data.Entity.DynamicProxies.User

my code is

  User ma = db.user.First(x => x.u_id == id);
  return Json(ma, JsonRequestBehavior.AllowGet);
1
12
1/29/2016 6:18:02 AM

Accepted Answer

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

  db.Configuration.ProxyCreationEnabled = false;
  User ma = db.user.First(x => x.u_id == id);
  return Json(ma, JsonRequestBehavior.AllowGet);
33
10/5/2014 7:29:12 PM

Popular Answer

My problem is solved by using this :

//initialize model db
testdbEntities dc = new testdbEntities();
//get employee details 
List<Employee1> lst = dc.Employee1.ToList(); 
//selecting the desired columns
var subCategoryToReturn = lst.Select(S => new {
    Employee_Id = S.Employee_Id,
    First_Name = S.First_Name,
    Last_Name = S.Last_Name,
    Manager_Id = S.Manager_Id
});
//returning JSON
return this.Json(subCategoryToReturn , JsonRequestBehavior.AllowGet);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow