[英]Entity to json error - A circular reference was detected while serializing an object of type
嘗試將實體對象轉換為 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<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);
我遇到了同樣的問題,我所做的是只通過了需要的列來查看,就我而言。 只有 2。
List<SubCategory> lstSubCategory = GetSubCateroy() // list from repo
var subCategoryToReturn = lstSubCategory.Select(S => new { Id = S.Id, Name = S.Name });
return this.Json(subCategoryToReturn , JsonRequestBehavior.AllowGet);
為什么不創建一個類來保存查詢內容? 那對我有用
它正在嘗試加載子對象,並且它可能會創建一些永遠不會結束的循環循環屬性。
你也使用 [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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.