Entity Framework 6 代码优先中的自引用

Self Referencing in Entity Framework 6 Code First

我的代码中有这些 class :

public class Parent
{
    [Key]
    public int ParentID { get; set; }
    public string ParentName { get; set; }
    public virtual ICollection<Child> Childs { get; set; }
}

public class Child
{
    [Key]
    public int ChildID { get; set; }
    public string ChildName { get; set; }
    public int ParentID { get; set; }
    [ForeignKey("ParentID")]
    public virtual Parent Parent { get; set; }
}

ParentChild 具有一对多关系,ChildParent 属性 具有一对多关系。以后会不会给我添麻烦?因为我在尝试使用 Newtonsoft 将此 class 转换为 JObject 时遇到 Self referencing loop detected 异常。我是否应该从 Child 中删除 Parent 属性 这样它就不会导致自引用?

问题是,当您序列化其中任何一个 类 时,您确实有一个循环引用。 parent 有一个 children 的列表,它又链接回 parent。

JsonIgnoreAttribute 修饰 Child.Parent,它将停止尝试序列化此 属性。它作为导航绝对有用 属性,但我想不出一个实际案例,您希望将整个 Parent object 序列化为 Child 的成员。 (不过,parent 的 ID 可能会有用。)

有两种方法可以处理这个错误。 首先,你可以忽略导航属性(虚拟ICollection)。因为。这是为了导航和序列化这个效果

Self referencing loop detected exception

这发生在 Newtonsoft 或 XmlSerializer 中。

其次,可以使用POCO class不使用代理进行序列化。