I\'m having problems with a circular reference when i try and serialise an object returned via EF4 CTP5. Im using the code first approach and simple poco\'s for my model.
No matter what I did the dynamic proxies kept being a sticking point, I went as far as removing all circular references in my model! but still the problem persisted.
I tried Json.Net but the same problem occurred.
In the end I stumbled upon a post about using a custom JavaScriptConverter
http://hellowebapps.com/2010-09-26/producing-json-from-entity-framework-4-0-generated-classes/
Implemented the code and bobs your uncle everything worked
I had a similar problem with an IIS hosted WCF service and trying to serialize POCO objects with the DataContractJsonSerializer class. The built in JSON serializer does not seem to handle circular references at all. I was able to get around it by handling the serialization myself using the JSON.net serializer, and just returning json strings from my methods. The JSON.net serializer has an option to ignore circular references as json itself does not support them.
I have met this issue too. Answers to this topic contains number solutions. But best different solutions for different cases with explanation and moreover without custom serializes I have found in the article by Hongye Sun - Loop Reference handling in Web API.
I used the following ContractResolver. Note that I inherited from the CamelCaseContractPropertyResolver to get that feature as well, but you can also inherit directly from DefaultContractResolver.
using System;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace MyNamespace
{
/// <summary>
/// This class enables EntityFramework POCO objects to be serialized. In some cases POCO
/// objects are subclassed by a proxy which has an additional member _entityWrapper. This
/// object prevents serialization (circular references and references to non-serializable types).
/// This removes the _entityWrapper from the list of members to be serialized.
/// </summary>
public class ContractResolver : CamelCasePropertyNamesContractResolver
{
protected override List<MemberInfo> GetSerializableMembers(Type objectType)
{
if (objectType.FullName.StartsWith("System.Data.Entity.DynamicProxies."))
{
var members = base.GetSerializableMembers(objectType);
members.RemoveAll(memberInfo => memberInfo.Name == "_entityWrapper");
return members;
}
return base.GetSerializableMembers(objectType);
}
}
}
To use it, create your serializer and then set the ContractResolver property to a new instance of this class:
var ser = JsonSerializer.Create(sJsonSerializerSettings);
ser.ContractResolver = new ContractResolver();
I solved this without having to resort to an external JSON serializer. In a nutshull I disabled ProxyCreation in the constructor of my object context.
I am not sure why this works but I posted a follow up question here.