對於兩張表A、B多對多的關系中,A的導航屬性中有B,B的導航屬性中有A,這樣Json.net對A或者B對象序列化時會形成死循環
所以對於導航屬性要加標簽
首先在A、B實體類工程(Model)中引用Json.ne
然后對導航屬性加不序列化標簽([JsonIgnore])
//------------------------------------------------------------------------------ // <auto-generated> // 此代碼是根據模板生成的。 // // 手動更改此文件可能會導致應用程序中發生異常行為。 // 如果重新生成代碼,則將覆蓋對此文件的手動更改。 // </auto-generated> //------------------------------------------------------------------------------ namespace CZBK.ItcastOA.Model { using System; using System.Collections.Generic; using Newtonsoft.Json; public partial class UserInfo { public UserInfo() { this.R_UserInfo_ActionInfo = new HashSet<R_UserInfo_ActionInfo>(); this.Department = new HashSet<Department>(); this.RoleInfo = new HashSet<RoleInfo>(); } public int ID { get; set; } public string UName { get; set; } public string UPwd { get; set; } public System.DateTime SubTime { get; set; } public short DelFlag { get; set; } public System.DateTime ModifiedOn { get; set; } public string Remark { get; set; } public string Sort { get; set; } [JsonIgnore] public virtual ICollection<R_UserInfo_ActionInfo> R_UserInfo_ActionInfo { get; set; } [JsonIgnore] public virtual ICollection<Department> Department { get; set; } [JsonIgnore] public virtual ICollection<RoleInfo> RoleInfo { get; set; } } }
但需要把引用以及
[JsonIgnore] public virtual ICollection<R_UserInfo_ActionInfo> R_UserInfo_ActionInfo { get; set; } [JsonIgnore] public virtual ICollection<Department> Department { get; set; } [JsonIgnore] public virtual ICollection<RoleInfo> RoleInfo { get; set; }
加入T4 模板中。
這樣在應用反序列化時,無法拿到導航屬性,只能再次查找數據庫!
----------------------------------------------------------------------------------------------
如果用微軟自帶的序列化解決辦法
序列化類型為xxx的對象時檢測到循環引用解決方法
方法一:關閉導航功能(不能再使用導航屬性)
public ActionResult Index() { testContext context = new testContext(); context.Configuration.ProxyCreationEnabled = false; var data = context.People; return Json(data, JsonRequestBehavior.AllowGet); }
方法二:轉為匿名對象
public ActionResult Index() { testContext context = new testContext(); var data = context.People.Select(item => new { item.Id, item.Name }); return Json(data, JsonRequestBehavior.AllowGet); }