【问题标题】:Why aren't my included entities actually included?为什么我包含的实体实际上并未包含在内?
【发布时间】:2014-02-20 23:33:59
【问题描述】:

我在 Visual Studio 2010 中使用 C# 中的 Entity Framework 4。

我有一个在存储库中使用的方法,它返回一个包含各种导航属性的对象集。直到最近,这种方法看起来像这样......

private IEnumerable<VRTSystem> GetSystems() {
  return ctx
    .Include(s => s.Customer.CustomerType)
    .Include(s => s.VRTSystemProductConfigurations);
}

...其中 ctx 是泛型类型 VRTSystem 的 ObjectSet。 full 方法的 .Include() 比这多得多,但这足以说明问题。

这很好用,但是我需要添加一些代码以确保只返回 Active 标志设置为 true 的 VRTSystemProductConfigurations。按照通常针对这种情况给出的建议,我将代码更改为如下所示...

private IEnumerable<VRTSystem> GetSystems() {
  return ctx
    .Include(s => s.Customer.CustomerType)
    .Include(s => s.VRTSystemProductConfigurations)
    .Select(s => new {
      System = s,
      VRTSystemProductConfigurations = s.VRTSystemProductConfigurations.Where(pc => pc.Active)
    })
    .Select(s => s.System);
}

但是,这个新版本不包含任何导航属性,它们都是空的。

有人知道为什么吗?

【问题讨论】:

    标签: c# entity-framework entity-framework-4


    【解决方案1】:

    这是因为实体框架并不完全愚蠢。它看到最后只查询了Systems,所以它切断了两者之间的所有内容,只返回Systems。您在这里执行的部分技巧是禁用延迟加载,因此导航属性为 null 并将保持为 null。

    您必须通过添加AsEnumerable 将最后一个Select 移出EF 查询提供程序的范围:

    return ctx
    .Include(s => s.Customer.CustomerType)
    .Select(s => new {
      System = s,
      VRTSystemProductConfigurations = s.VRTSystemProductConfigurations.Where(pc => pc.Active)
    })
    .AsEnumerable() 
    .Select(s => s.System);
    

    您不想包含VRTSystemProductConfigurations,因为这是您要部分加载的集合。

    【讨论】:

    • 嗯,不知道我现在做了什么,但我确定我在尝试解决这个问题时曾经有 AsEnumerable() 存在。这是正常做法的一部分。请问是不是我放错地方了?无论如何,我按照您的说明添加了它,现在可以使用了,非常感谢。但是,我不确定您为什么认为我不想包含 VRTSystemProductConfigurations。也许我应该指出我们禁用了延迟加载,因为这些实体是通过 WCF 发送的,所以必须急切地包含所有内容。不知道这是否会改变事情。如果不是,请解释为什么你认为我应该包括它们。
    • 因为你只想加载活跃的VRTSystemProductConfigurations,不是吗? Include 不会加载所有这些吗?
    • 是的,但是由于延迟加载已关闭,如果我不使用包含,那么它不会加载任何一个。据我所知,这是不使用延迟加载的唯一方法。
    • 重点是您分别加载活动项目,EF 通过relationship fixup 将它们拼接在一起。与此同时,我发现Include 无效。它不会加载整个集合,Active 谓词仍在评估中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    相关资源
    最近更新 更多