实体到json错误 – 在序列化类型的对象时检测到循环引用
尝试将实体对象转换为JSON字符串时发生以下错误。 我正在使用C#MVC4代码首先进行数据库设计。 因为FK和表之间的关系会产生这个问题。 解决方法是什么?
序列化System.Data.Entity.DynamicProxies.User类型的对象时检测到循环引用
我的代码是
User ma = db.user.First(x => x.u_id == id); return Json(ma, JsonRequestBehavior.AllowGet);
因为它试图加载子对象,它可能会创建一个永远不会结束的圆形循环(a => b,b => c,c => d,d => a)
您可以仅在特定时刻关闭它,如下所示。除非在您的对象上调用Include方法,否则dbcontext不会加载客户子对象
db.Configuration.ProxyCreationEnabled = false; User ma = db.user.First(x => x.u_id == id); return Json(ma, JsonRequestBehavior.AllowGet);
我的问题通过使用这个来解决:
//initialize model db testdbEntities dc = new testdbEntities(); //get employee details List 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);
我遇到了同样的问题,我所做的只是通过了需要的列来查看,在我的情况下。 只有2。
List lstSubCategory = GetSubCateroy() // list from repo var subCategoryToReturn = lstSubCategory.Select(S => new { Id = S.Id, Name = S.Name }); return this.Json(subCategoryToReturn , JsonRequestBehavior.AllowGet);
循环引用在将对象序列化为JSON时检测到exception
它试图加载子对象,它可能会创建一些永远不会结束的循环循环属性。
你也使用[ScriptIgnore],不会序列化公共属性或公共字段看看:
public class BookingHotel : IntBaseEntity { public string BookingName { get; set; } public string BookingReference { get; set; } public DateTime? CheckInDate { get; set; } public DateTime? CheckOutDate { get; set; } public int HotelId { get; set; } [ScriptIgnore] public Hotel Hotel { get; set; } }
为什么不创建一个类来保存查询内容? 这对我有用