Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

JSON.NET Error Self referencing loop detected for type

I tried to serialize POCO class that was automatically generated from Entity Data Model .edmx and when I used
JsonConvert.SerializeObject 

I got the following error:

Error Self referencing loop detected for type System.data.entity occurs.

How do I solve this problem?
by

2 Answers

akshay1995
The simplest way to do this is to install Json.NET from nuget and add the [JsonIgnore] attribute to the virtual property in the class, for example:

public string Name { get; set; }
public string Description { get; set; }
public Nullable<int> Project_ID { get; set; }

[JsonIgnore]
public virtual Project Project { get; set; }

Although these days, I create a model with only the properties I want passed through so it's lighter, doesn't include unwanted collections, and I don't lose my changes when I rebuild the generated files...
RoliMishra
In .NET Core 1.0, you can set this as a global setting in your Startup.cs file:

using System.Buffers;
using Microsoft.AspNetCore.Mvc.Formatters;
using Newtonsoft.Json;

// beginning of Startup class

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings(){
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
}, ArrayPool<char>.Shared));
});
}

Login / Signup to Answer the Question.