【发布时间】:2015-10-22 13:44:16
【问题描述】:
我在尝试通过 Web API 返回 Entity Framework 6 生成的递归序列化对象时遇到问题。这是我的问题的一个小例子:
[Serializable]
[DataContract]
public partial class Thing
{
public Thing()
{
this.OtherThings = new HashSet<OtherThings>();
}
[DataMember]
public int ThingId { get; set; }
[DataMember]
public string ThingName { get; set; }
//Not included in serialization
public virtual ICollection<OtherThing> OtherThings { get; set; }
}
[Serializable]
[DataContract]
public partial class OtherThing
{
public OtherThing()
{
this.Things = new HashSet<Things>();
}
//I want these
[DataMember]
public int OtherThingId { get; set; }
[DataMember]
public string OtherThingName { get; set; }
//Do NOT want this from GetAllThings() to avoid circular references
public virtual ICollection<Things> Things { get; set; }
}
装饰器是从 Context.tt 文件生成的,并且在我的真实对象中还有 很多 属性,因此无法手动编辑这些属性 - 更不用说这些文件是自动的 -生成。
我用这个简单的方法从我的数据库中检索Things 的集合:
public static class Repo {
internal static IQueryable<Thing> GetAllThings()
{
//Context is an initialized database context
return Context.Things;
}
}
返回Things 的整个集合,其中包含OtherThings,每个集合都包含更多Things。当我尝试将其序列化为 Web API 响应时,问题变得很明显:
public class API {
//This response is serialized to JSON
public List<Thing> GetAllThings()
{
var things = Repo.GetAllThings();
//Do something here to exclude
return things.ToList();
}
}
序列化器自然会失败(或溢出),因为存在循环引用。通常我会将[DataIgnore] 添加到有问题的属性中而完全忘记DataContracts,但如果我请求Things 的集合,我只想要每个连接的OtherThing,反之亦然。
这个可以吗?
【问题讨论】:
标签: c# entity-framework serialization