实体框架中的自引用6代码优先

时间:2015-08-25 15:22:47

标签: c# entity-framework ef-code-first entity-framework-6

我的代码中有这些类:

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; }
}

ParentChildChild具有Parent属性的一对多关系。这会不会给我带来麻烦?因为我尝试使用Newtonsoft将此类转换为Self referencing loop detected时遇到JObject异常。我想从Parent中删除Child属性,这样就不会引起自我引用吗?

2 个答案:

答案 0 :(得分:2)

问题是当你去序列化这些类中的任何一个时,你确实有一个循环引用。父母有一个孩子的列表,这些孩子又链接回父母。

使用JsonIgnoreAttribute装饰Child.Parent,它将停止尝试序列化此属性。它作为导航属性绝对有用,但我不能想到一个单一的实际案例,你希望将整个Parent对象序列化为Child的成员。 (父母的id可能会有用。)

答案 1 :(得分:0)

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

  

自我引用循环检测到异常

这发生在Newtonsoft或XmlSerializer。

其次,您可以使用不带代理的POCO类来序列化。

相关问题