Self Referencing in Entity Framework 6 Code First

c# ef-code-first entity-framework entity-framework-6

Question

I have these class in my code :

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

Parent have one-to-many relationship with Child and Child have Parent property. Is this going to cause me trouble in the future? Because I just got Self referencing loop detected exception when trying to convert this class into JObject with Newtonsoft. Am I suppose to remove Parent property from Child so it doesn't cause self referencing?

1
1
8/25/2015 3:22:47 PM

Accepted Answer

The problem is you indeed have a circular reference when you go to serialize either one of these classes. The parent has a list of children which in turn links back to the parent.

Decorate Child.Parent with a JsonIgnoreAttribute and it will stop trying to serialize this property. It's definitely useful as a navigation property but I can't think of a single practical case you'd want the entire Parent object serialized as a member of a Child. (The parent's id might be useful to keep though.)

2
8/25/2015 3:38:15 PM

Popular Answer

There is two way to handle this error. First, you can ignore navigation property (virtual ICollection). Because. this is for navigation and serializing this effects

Self referencing loop detected exception

This occurs either Newtonsoft or XmlSerializer.

Second, you can use POCO class without proxy to serialize.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow