[Solved-5 Solutions] Error Self referencing loop detected for type System.data.entity occurs



Error Description:

    • When we try to serialize POCO class that was automatically generated from Entity Data Model .edmx and when we use
    JsonConvert.SerializeObject 
      
    click below button to copy the code. By - json tutorial - team
    • We get the following error:

    Error Self referencing loop detected for type System.data.entity

    Solution 1:

    Ignoring circular reference globally

    • json.net serializer supports to ignore circular reference on global setting. A quick fix is to put following code in WebApiConfig.cs file:
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
    = Newtonsoft.Json.ReferenceLoopHandling.Ignore; 
      
    click below button to copy the code. By - json tutorial - team
    • The simple fix will make serializer to ignore the reference which will cause a loop. However, it has limitations:
    • The data loses the looping reference information this fix only applies to JSON.net The level of references can't be controlled if there is a deep reference chain.

    Solution 2:

    • Just change the code to:
    config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling 
         = Newtonsoft.Json.ReferenceLoopHandling.Serialize;     
    config.Formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling 
         = Newtonsoft.Json.PreserveReferencesHandling.Objects;
      
    click below button to copy the code. By - json tutorial - team
    • The data shape will be changed after applying this setting.
    [
       {
          "$id":"1",
          "Category":{
             "$id":"2",
             "Products":[
                {
                   "$id":"3",
                   "Category":{
                      "$ref":"2"
                   },
                   "Id":2,
                   "Name":"Yogurt"
                },
                {
                   "$ref":"1"
                }
             ],
             "Id":1,
             "Name":"Diary"
          },
          "Id":1,
          "Name":"Whole Milk"
       },
       {
          "$ref":"3"
       }
    ]
      
    click below button to copy the code. By - json tutorial - team
    • The $id and $ref keeps all the references and makes the object graph level flat, but the client code needs to know the shape change to consume the data and it only applies to JSON.NET serializer as well.

    Solution 3:

    Ignore and preserve reference attributes

    • This fix is decorate attributes on model class to control the serialization behavior on model or property level. To ignore the property:
     public class Category 
        { 
            public int Id { get; set; } 
            public string Name { get; set; } 
            
            [JsonIgnore] 
            [IgnoreDataMember] 
            public virtual ICollection<Product> Products { get; set; } 
        } 
      
    click below button to copy the code. By - json tutorial - team
    • JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:
     // Fix 3 
        [JsonObject(IsReference = true)] 
        public class Category 
        { 
           public int Id { get; set; } 
            public string Name { get; set; } 
         
            // Fix 3 
            //[JsonIgnore] 
           //[IgnoreDataMember] 
           public virtual ICollection<Product> Products { get; set; } 
       } 
        
       [DataContract(IsReference = true)] 
       public class Product 
       { 
          [Key] 
           public int Id { get; set; } 
        
           [DataMember] 
           public string Name { get; set; } 
        
           [DataMember] 
           public virtual Category Category { get; set; } 
       } 
      
    click below button to copy the code. By - json tutorial - team
    • JsonObject(IsReference = true)] is for JSON.NET and [DataContract(IsReference = true)] is for XmlDCSerializer. Note that: after applying DataContract on class, we need to add DataMemberto properties that you want to serialize.
    • The attributes can be applied on both json and xml serializer and gives more controls on model class.

    Solution 4:

    Use JsonSerializerSettings

    • ReferenceLoopHandling.Error (default) will error if a reference loop is encountered. This is why you get an exception.
    • ReferenceLoopHandling.Serialize is useful if objects are nested but not indefinitely.
    • ReferenceLoopHandling.Ignore will not serialize an object if it is a child object of itself.

    Example:

    JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
    new JsonSerializerSettings { 
            ReferenceLoopHandling = ReferenceLoopHandling.Serialize
    });  
    click below button to copy the code. By - json tutorial - team
    • We should have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid Exception.

    Example:

    JsonConvert.SerializeObject(YourPOCOHere, Formatting.Indented, 
    new JsonSerializerSettings { 
            PreserveReferencesHandling = PreserveReferencesHandling.Objects
    });  
    click below button to copy the code. By - json tutorial - team

    Solution 5:

    • We can add these two lines into DbContext class constructor to disable Self referencing loop, like
    public TestContext()
            : base("name=TestContext")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }
    
      
    click below button to copy the code. By - json tutorial - team

    Related Searches to Error Self referencing loop detected for type System.data.entity occurs