1

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?

tickwave
  • 3,335
  • 6
  • 41
  • 82
  • Please have a look at my answer on **[“Self Referencing Loop Detected” exception with JSON.Net](https://stackoverflow.com/questions/40472419/self-referencing-loop-detected-exception-with-json-net/51235783#51235783)** page. – Murat Yıldız Jul 08 '18 at 20:38

2 Answers2

2

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.)

lc.
  • 113,939
  • 20
  • 158
  • 187
  • Alright, but let's ignore about newtonsoft and talk about my EF `dbSet` design, is this a common design or I'm doing it wrong? – tickwave Aug 25 '15 at 15:33
  • 1
    It's fine. You have a reverse navigation property and it operates exactly like you think it will. This is very common, although I sometimes omit it at first if I don't think I will traverse the hierarchy backwards. – lc. Aug 25 '15 at 15:35
0

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.

Engineert
  • 192
  • 1
  • 1
  • 16