It’s very typical for Entity Framework models to have circular references. For example:
public class Author { public Author() { Articles = new Collection<Article>(); } public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public virtual ICollection<Article> Articles { get; set; } } public class Article { public int Id { get; set; } public string Title { get; set; } public virtual Author Author { get; set; } }
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.
[Route("GetArticles")] [HttpGet] public IHttpActionResult Get() { return Ok(dbContext.Articles); }
There are a few solutions to solve this error:
- The quick fix is ignoring circular referencing globally. Simply set ReferenceLoopHandling in the serialiser settings in WebApiConfig.cs to Ignore
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- Disable EF proxy creation in the database context’s constructor
this.Configuration.ProxyCreationEnabled = false;
- 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.