Json.net serialisation issue when returning Entity Framework models in Web API

It’s very typical for Entity Framework models to have circular references. For example:

This, however, will cause serialisation error when returning these EF models in Web API controller because it detects that there are circular references. The json serialiser does not know how to handle circular reference.

There are a few solutions to solve this error:

  1. The quick fix is ignoring circular referencing globally. Simply set ReferenceLoopHandling in the serialiser settings in WebApiConfig.cs to Ignore
  2. Disable EF proxy creation in the database context’s constructor
  3. Create DTOs with the only the required properties and return those in the controller actions instead of returning the EF models directly.

I would go with the third solution because it does not return more data than required and it does not expose the structure of the database.

Like this post?

Leave a Reply

Your email address will not be published. Required fields are marked *