Entity Frameworks, WebApi, JSON.Net and Serializing Circular References – Better fix

As an improvement on yesterday problem and solution, there is a simple change to the JSON.Net settings which solves this issue, just add this into Global.asax:

JsonSerializerSettings settings = new JsonSerializerSettings
{
    PreserveReferencesHandling = PreserveReferencesHandling.Objects,
    Formatting = Formatting.Indented
};
 
HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings = settings;
Advertisements

Entity Frameworks, WebApi, JSON.Net and Serializing Circular References

While Entity Frameworks handles circular references between models very well, putting them through a WebApi web service and serializing them, Json.Net starts throwing errors.

The quickest way around this is to rebuild the objects and miss out the references from the child back to the parent.

 
public virtual HttpResponseMessage Get()
{
var data = ADRepository.GetAllocatedApplications();

// do this to get around the bloody annoying Json Circular References Issue
List result = data.Select(x => new ActiveDirectoryGroup
{
Id = x.Id,
Name = x.Name,
IsDeleted = x.IsDeleted,
LastUpdated = x.LastUpdated,
LastUpdatedBy = x.LastUpdatedBy,
Applications = x.Applications.Select(y => new Application
{
Id = y.Id,
Name = y.Name,
CommandLine = y.CommandLine,
IsDeleted = y.IsDeleted,
LastUpdated = y.LastUpdated,
LastUpdatedBy = y.LastUpdatedBy
}).ToList()
}).ToList();

return Request.CreateResponse<List>(System.Net.HttpStatusCode.OK, result);
}