【问题标题】:How to use Include() after OfType()?如何在 OfType() 之后使用 Include()?
【发布时间】:2012-08-23 05:38:45
【问题描述】:

我正在尝试在实体框架模型中急切加载派生类的属性。

我读到 all over the place 我必须先用 OfType() 过滤集合,然后再用 Include() 包含属性:

var persons = Context.Persons
                     .OfType<Employee>()
                     .Include("Compensation")

我不知道如何让 Include() 工作,因为在我的例子中,Persons 是一个 DbSet,OfType() 返回一个 IQueryable,而 IQueryable 没有定义 Include() 方法。

【问题讨论】:

标签: c# .net entity-framework entity-framework-5


【解决方案1】:

放置这个:

using System.Data.Entity;

进入您的使用列表,之后您将能够使用来自DbExtensions 类的Include 扩展方法系列:

    public static IQueryable<T> Include<T, TProperty>(this IQueryable<T> source, Expression<Func<T, TProperty>> path) where T : class;
    public static IQueryable<T> Include<T>(this IQueryable<T> source, string path) where T : class;
    public static IQueryable Include(this IQueryable source, string path);

他们接受 IQueryable 作为第一个参数,也有强类型的,这更好,然后Include(String)

【讨论】:

  • 啊!谢谢,我认为这可能是一种扩展方法。我真的希望 VS 使命名空间可被发现和/或人们在他们的示例中包含 usings :)
  • @XavierPoinas:完全同意你的观点,这让我第一次也感到困惑。
  • @XavierPoinas 由于这个(以及其他)原因,我已转换为 Resharper。 Resharper 将建议扩展方法来填补 intellisense 中 Visual Studios 建议中的这一缺失。完全同意你的看法!
  • @TheSenator 实际上 VS 2015 现在也这样做了,所以我现在很高兴 :-)
  • @XavierPoinas:是的。最终,VS 将杀死 R#。 :)
猜你喜欢
  • 2020-10-18
  • 1970-01-01
  • 2016-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
相关资源
最近更新 更多