Few days ago, I was creating an ASP.NET Web API by generating Entity Framework scaffolding API controller. There were simply two tables in the database Product and Title. In the edmx file, the auto-generated classes were as follows:
public partial class Product
{
public Product()
{
this.Titles = new HashSet<Title>();
}
public long ID { get; set; }
public string Name { get; set; }
public string ItemCode { get; set; }
public string StatusCode { get; set; }
public string Description { get; set; }
public virtual ICollection<Title> Titles { get; set; }
}
public partial class Title
{
public long ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public virtual Product Product { get; set; }
}
In the ApiController file, I had a Get method which returned Parent (Product) and Child (Title) data. The definition for Get method is as follows.
public IEnumerable<Product> Get()
{
return entities.Products.Include(x => x.Titles).AsEnumerable();
}
Just after I hit Web API URL in the browser, I started getting following error message.
Error Message
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
Self referencing loop detected for property 'Product' with type 'System.Data.Entity.DynamicProxies.Product_51E58E5D9B59C792A692C1D0BD14B81033E09B8451A77CDC684C1AA673008663'. Path '[0].Titles[0]'.
This issue was occurring because I was trying to serialize the Entity Framework object directly. Since Product have Titles and the Titles have a reference back to Product, it cannot be serialized. After spending some time, I found the solution which required me to add following lines in Application_Start() method in Global.asax.cs file.
Solution
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter
.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Here we have defined global setting for JSON.Net serializer to ignore circular references.
2 Comment(s)