【问题标题】:Entity Framework Include without nested properties没有嵌套属性的实体框架包含
【发布时间】:2018-02-08 21:32:52
【问题描述】:

我有两个相关的实体,称为 DataTag 和 TagSource,如下所示:

public class DataTag : BaseModel
{
    [Column("DataTagId")]
    public override Guid ID { get; set; }
    public string Tag { get; set; }

    public Guid TagSourceId { get; set; }
    public TagSource TagSource { get; set; }
}

public class TagSource : BaseModel
{
    [Column("TagSourceId")]
    public override Guid ID { get; set; }
    public string Description { get; set; }
    public bool IsInternal { get; set; }
    public string Source { get; set; }

    public ICollection<DataTag> DataTags { get; set; }
}

我允许用户通过“/api/DataTags?Include=TagSource”之类的 url 包含导航属性。问题是当我包含 TagSource 时,它​​还包含该对象中我不想要的 DataTag 集合,除非用户指定它(例如“/api/DataTags?Include=TagSource.DataTags”。有什么办法吗?当我包含 TagSource 时阻止该属性被加载?我尝试将属性设为虚拟并在全局范围内关闭延迟加载,但这不起作用。我没有将它们标记为虚拟的原因是因为我正在使用 AutoMapper只想包含用户指定的导航属性。

【问题讨论】:

  • 把它投影到别的东西上。您的问题是 WebAPI 序列化了您返回的整个对象。
  • 将 DTO 与您想要返回给用户的数据一起使用
  • 你能显示 URL 映射到的操作方法吗?我不明白禁用延迟加载仍然会加载导航属性。

标签: c# entity-framework asp.net-web-api


【解决方案1】:

在 cmets 中,您需要创建一个 DTO 对象。这里有一篇很好的文章详细介绍了如何使用 WebAPI 来做到这一点

http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-5

编辑。

这样做的问题是,对于每个可能的结果,您都需要很多不同的 DTO 对象,这可能会变得混乱。如果您的返回类型是 JSON,您可以将此属性添加到您的属性中:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

【讨论】:

  • 他可以使用反射来填充一个字典,该字典只表示他实际想要序列化的对象图的部分。
【解决方案2】:

首先:为我的英语道歉。

其次:我对以这种方式创建外键的代码优先数据库模型有同样的问题:public virtual Collection&lt;Object&gt; Objects {get; set;}

我通过将属性设置器设置为私有找到了解决方法:

public virtual Collection<Object> Objects {get; private set;}

然后 EF 无法填充 Objects 集合,因为使用私有集合只能在构造函数中赋值。

【讨论】:

    猜你喜欢
    • 2013-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多