我已經閱讀了很多此問題的解決方案,但都沒有爲我工作。檢測到自檢迴路
我有事件和用戶對象之間的循環關係:
public class Event : EntityData
{
[Required]
[ForeignKey("Creator")]
public string CreatorId { get; set; }
public User Creator { get; set; }
[InverseProperty("ParticipantIn")]
public virtual ICollection<User> Participants { get; set; }
[InverseProperty("ManagerIn")]
public virtual ICollection<User> Managers { get; set; }
}
正如你可以看到我有這個類用戶三個參考:事件的創造者,管理人員的名單,和與會者名單。
用戶類包含對事件的引用,以及:
public class User: EntityData
{
[InverseProperty("Participants")]
public virtual ICollection<Event> ParticipantIn { get; set; }
[InverseProperty("Managers")]
public virtual ICollection<Event> ManagerIn { get; set; }
}
現在,問題是,當我試圖序列的事件,就像在我createEvent功能,它告訴我,有一個自我引用循環,這是因爲當創建事件時,我將它添加到創作者的'ManagerIn'集合中。
這行導致事件 - >創建器> ManagerIn->事件 - >創作者 - > ..... LOOP
我想什麼,我也有一個版本的代碼的公共虛擬用戶的創造者,爲了使其加載懶洋洋地..
現在,我的解決方案是非常不優雅,事件返回到客戶端之前,我執行:
event.Creator = null;
和
event.Managers = null;
爲了避免自引用循環。
解決這類問題的正確方法是什麼?
在此先感謝, Liran!
你用什麼來序列化它? – Evk
如果您使用的是XML http://stackoverflow.com/questions/5004397/is-it-possible-to-perform-serialization-with-circular-references可能是相關的 – Chris
http://stackoverflow.com/questions/ 26434738 /你怎麼真的序列化循環引用對象與牛頓軟件json可能是有趣的json – Chris