EF 4.1 - Code First - JSON Circular Reference Serialization Error

Solution 1:

You could try to remove the virtual keyword from all navigation properties to disable lazy loading and proxy creation and then use eager loading instead to load the required object graph explicitely:

public ActionResult GetAll()
{
    return Json(ppEFContext.Orders
                           .Include(o => o.Patient)
                           .Include(o => o.Patient.PatientAddress)
                           .Include(o => o.CertificationPeriod)
                           .Include(o => o.Agency)
                           .Include(o => o.Agency.Address)
                           .Include(o => o.PrimaryDiagnosis)
                           .Include(o => o.ApprovalStatus)
                           .Include(o => o.Approver)
                           .Include(o => o.Submitter),
        JsonRequestBehavior.AllowGet);
}

Referring to your previous post it looks like your application isn't relying on lazy loading anyway because you introduced there the virtual properties to load the object graph lazily, possibly causing now the serialization trouble.

Edit

It's not necessary to remove the virtual keyword from the navigation properties (which would make lazy loading completely impossible for the model). It's enough to disable proxy creation (which disables lazy loading as well) for the specific circumstances where proxies are disturbing, like serialization:

ppEFContext.Configuration.ProxyCreationEnabled = false;

This disables proxy creation only for the specific context instance ppEFContext.

(I've just seen, @WillC already mentioned it here. Upvote for this edit please to his answer.)

Solution 2:

When you know that you need to serialize from a particular context, you can disable proxy creation for that particular query like below. This has worked for me and is better than revising my model classes.

using (var context = new MeContext())
{
    context.Configuration.ProxyCreationEnabled = false;
    return context.cars.Where(w => w.Brand == "Ferrari")
}

This approach takes away the proxy object type for this particular instance of the context so the returned objects are the actual class and therefore serialization is not a problem.

ie:

{Models.car} 

instead of

{System.Data.Entity.DynamicProxies.car_231710A36F27E54BC6CE99BB50E0FE3B6BD4462EC‌​A19695CD1BABB79605296EB} 

Solution 3:

The problem is that your are actually serializing an entity framework generated proxy object. Unfortunatly this has some issues when used with the JSON serializer. You might consider to map your entities to special simple POCO classes for the sake of JSON compatibility.

Solution 4:

There is an attribute to add to Entity Framework objects

[ScriptIgnore]

This makes the code not perform Circular references.