我只是按照非常简单的示例进行了操作,并且ProxyDataContractResolver
按预期工作-具有周期的代理实体图已正确序列化。
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Objects;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
namespace CFSerialization
{
class Program
{
static void Main(string[] args)
{
using (var context = new Context())
{
context.Database.Delete();
context.Database.CreateIfNotExists();
context.Masters.Add(new Master
{
Name = "abc",
Details = new List<Detail>
{
new Detail { Name = "a" },
new Detail { Name = "b" },
new Detail { Name = "c" }
}
});
context.SaveChanges();
}
using (var context = new Context())
{
// This will get proxied Master
var master = context.Masters.First();
var serializer = new DataContractSerializer(typeof(Master), new DataContractSerializerSettings()
{
DataContractResolver = new ProxyDataContractResolver()
});
using (var stream = new MemoryStream())
{
// This will also lazy load all details
serializer.WriteObject(stream, master);
stream.Seek(0, SeekOrigin.Begin);
var newMaster = (Master)serializer.ReadObject(stream);
}
}
}
}
[DataContract(IsReference=true)]
public class Master
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public virtual ICollection<Detail> Details { get; set; }
}
[DataContract(IsReference=true)]
public class Detail
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public virtual Master Master { get; set; }
}
public class Context : DbContext
{
public DbSet<Master> Masters { get; set; }
}
}
您的模型中必须有更复杂的东西来破坏功能 - 您的所有实体都标有DataContract(IsReference=true)
吗?
注意:我在 .NET 4.5 中对其进行了测试。