A circular reference error was detected while serializing an object of type XXXXX.
For example, when you try to access the MVC action as follows.
The request will sometimes get failed and the error messages will be thrown is as follows.
Response Circular reference error
The circular reference error will occur when serializing the POCO entities which refers each other. For example consider the relationship between the entities Order and Customer. Here the Order and Customer relation are referenced each other.
Figure 1: Relationship between Order and Customer relation
When the JSON serializer tries to serialize the entity object “Orders” with above relation it will try to serialize it`s relational object “Customers” and while traversing the “Customers” object it discovers circular reference and throws circular reference exception.
When using EF or LINQ to SQL, the circular reference error can be resolved using one of the following ways.
Setting the visibility of the Navigation property
If Entity Framework is used, then set the visibility of the navigation property as internal in the properties window as follows.
Entity Framework: Setting access as internal for navigation property
When using EF, you can also disable the proxy creation as follow to prevent proxy generation, which will avoid the circular reference error.
For LINQ to SQL, set the ChildProperty as false or set the Access as internal in the properties window of the particular relationship.
LINQ to SQL: Setting access as internal for navigation property
Using Data transfer object or View model
This is the most recommended and safe way to avoid circular reference error, as it involves serializing only the required properties without exposing the POCO entity directly.
Other than avoiding circular reference error, it also helps in making the object light weight by excluding properties which are meant to seen by client which in turn reduces payload size while transferring.
The ViewModel/DTO can be used as follows.
Result using view model/ DTO.
|Article ID:||Published Date:||Last Revised Date:||Platform:||Control:|
|6291||02/15/2016||02/15/2016||ASP.NET Web Forms||Grid|