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.>
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
{
///
/// 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.
///
public class ContractResolver : CamelCasePropertyNamesContractResolver
{
protected override List 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();