I have been struggling with this for a few days now, not finding any joy in any solutions I have found so far.
The project is built using Entity Framework 6 and WebAPI 2. I have changed the my WebApiConfig settings to
config.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
There seems to be an infinite loop happening now with a System Out Of Memory Exception being thrown.
I cant seem to find the correct way to do this.
I have tried this within the WebAPI Method too, still the same symptom.
public async Task<IHttpActionResult> GetCustomer_Title(int id)
{
Customer_Title c = await db.Customer_Title.FindAsync(id);
if (c == null)
{
return NotFound();
}
var json = JsonConvert.SerializeObject(c, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return Ok(json);
}
and in my Customer_Title Class
public partial class Customer_Title
{
public Customer_Title()
{
Customer = new HashSet<Customer>();
}
[Key]
public int TitleID { get; set; }
[Required]
[StringLength(100)]
public string TitleDescription { get; set; }
public int InstanceID { get; set; }
[JsonIgnore]
public virtual ICollection<Customer> Customer { get; set; }
public virtual System_Instance System_Instance { get; set; }
}
The [JsonIgnore] Attribute seems to be doing nothing.
You should use DTO instead of Entity framework entity, For example:
class PersonDTO {
public Name {get; set;}
}
var person = context.People.First();
var personDTO = new PersonDTO{
Name = person.Name
}
var json = new JavaScriptSerializer().Serialize(personDTO);