I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used
JsonConvert.SerializeObject
I got the following error:
Error Self referencing loop detected for type System.data.entity occurs.
How do I solve this problem?
Best Answer
That was the best solution https://docs.microsoft.com/en-us/archive/blogs/hongyes/loop-reference-handling-in-web-api
Fix 1: Ignoring circular reference globally
(I have chosen/tried this one, as have many others)
The json.net serializer has an option to ignore circular references. Put the 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:
If you want to use this fix in a non-api ASP.NET project, you can add the above line to
Global.asax.cs
, but first add:If you want to use this in .Net Core project, you can change
Startup.cs
as:Fix 2: Preserving circular reference globally
This second fix is similar to the first. Just change the code to:
The data shape will be changed after applying this setting.
The $id and $ref keeps the 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.
Fix 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, you 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.