Entity Framework Object Serialization error: Circular reference detected

Source: Internet
Author: User
Tags json object serialization serialization

The ASP.net MVC3 attempted to serialize the Entity Framework object, resulting in an error with the following code:

The code is as follows Copy Code

Public ActionResult Index ()
{
TestContext context = new TestContext ();
var data = context. People;
return Json (data, jsonrequestbehavior.allowget);
}

Error message:


Reference content
The serialization type is System.Data.Entity.DynamicProxies.Person_ 896262438f25ff951ff9f66bd7be34f10a8a5d962769864829136bf959f99a37 A circular reference was detected when the object was ".

The error is caused by the EF navigation attribute, the Pets property of the person object refers to the person object to cause an infinite loop, many problems in the EF can be solved after tolist, but not this time:

The code is as follows Copy Code

Public ActionResult Index ()
{
TestContext context = new TestContext ();
var data = context. People.tolist ();
return Json (data, jsonrequestbehavior.allowget);
}


Circular reference resolution detected when serializing an object of type XXX

Method One: Turn off navigation (navigation properties are no longer available)

The code is as follows Copy Code


Public ActionResult Index ()
{
TestContext context = new TestContext ();
Context. configuration.proxycreationenabled = false;
var data = context. People;
return Json (data, jsonrequestbehavior.allowget);
}

Method Two: Convert to anonymous object


  code is as follows copy code
public ActionResult Index ()
{
    testcontext context = new TestContext ();
    var dat A = context. People.select (item => new {item). Id, item. Name});
    return Json (data, jsonrequestbehavior.allowget);
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.