JavaScriptSerializer: Circular Reference was Detected While Serializing an Object of Type...

Consider an ASP.net MVC web application where you use some Ajax for retrieving an object. Let's start from the server-side MVC controller:


public class BaseDataController : Controller
{
private DataRepository repository;

public BaseDataController()
{
repository = new DataRepository();
}

public JsonResult GetOperationDefinitionByCode(string operationCode)
{
return Json(repository.GetOperationDefinitionByCode(operationCode), JsonRequestBehavior.AllowGet);
}
}

public class DataRepository
{
private EntityContext context;
...

public OperationDefinition GetOperationDefinitionByCode(string operationCode)
{
return context.OperationDefinitions.Where(x => x.OperationCode == operationCode).FirstOrDefault();
}
}
So far, so good. Now you call your controller via a GET request, like http://localhost:40492/basedata/getoperationdefinitionbycode/?operationCode=120. This will call your method, but unfortunately it returns an exception:
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.OperationDefinition_12123132123....'

The issue here - at least in my case - was the new DbContext T4 template for generating the EntityFramework entities. In order to be able to perform the change tracking, this templates uses the Proxy pattern, by wrapping your nice POCOs with them. This then causes the issues when serializing with the JavaScriptSerializer.

Now there are two solution possibilities. Either you just serialize and return the properties you need on the client, like
public class BaseDataController : Controller
{
private DataRepository repository;

public BaseDataController()
{
repository = new DataRepository();
}

public JsonResult GetOperationDefinitionByCode(string operationCode)
{
OperationDefinition result = repository.GetOperationDefinitionByCode(operationCode);
return Json(
new
{
Description = result.Description
},
JsonRequestBehavior.AllowGet);
}
}
Alternatively you may switch off the automatic generation of proxies by setting it on the context's configuration:
context.Configuration.ProxyCreationEnabled = false;
Kindle

Comments

0

Your ad here?