We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on : Nov 16th 2018).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Circular reference error while using Entity Framework/Linq 2 SQL.

Problem

                 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

 

Cause

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

 

Solution

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
Did you find this information helpful?
Add Comment
You must log in to leave a comment

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon