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); } |