【问题标题】:Serializing collections only one level deep with Entity Framework使用实体框架仅将集合序列化一层
【发布时间】: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


    【解决方案1】:

    假设 Context.Things 是您可以使用的 DbSet 类型

    return Context.Things.Select(s => s).Include(s => s.OtherThings);
    

    【讨论】:

    • 嗯,我试了一下,但似乎序列化程序非常持久,并且不关心 Include-d 的查询是什么。 EF6 模板还生成 HashSet,我编辑了我的问题以包含它。不过谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 2017-09-20
    • 1970-01-01
    • 2012-02-08
    • 2016-02-24
    相关资源
    最近更新 更多