C# – Entity to json error – A circular reference was detected while serializing an object of type

asp.net-mvc-4centity-frameworkjsonnet

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);

Best 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);