[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
- 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:
- 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:
- The data shape will be changed after applying this setting.
- 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:
- JsonIgnore is for JSON.NET and IgnoreDataMember is for XmlDCSerializer. To preserve reference:
JsonObject(IsReference = true)]
is for JSON.NET and[DataContract(IsReference = true)]
is for XmlDCSerializer. Note that: after applyingDataContract
on class, we need to addDataMember
to 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:
- We should have to serialize an object that is nested indefinitely you can use PreserveObjectReferences to avoid Exception.
Example:
Solution 5:
- We can add these two lines into DbContext class constructor to disable Self referencing loop, like