【问题标题】:EF Core 5 - Extension method on filter includeEF Core 5 - 过滤器的扩展方法包括
【发布时间】:2020-08-29 19:46:48
【问题描述】:

我正在 EF Core 5(预览版 3)上尝试新的、很棒且最终实现的“过滤包含”。

这段代码运行良好

var categoriesWithActiveProducts = await _context.Categories.Include(x => x.Products.Where(y => y.IsActive)).ToListAsync();

好吧,现在我想用一个扩展方法让代码更直观,所以

var categoriesWithActiveProducts = await _context.Categories.Include(x => x.Products.ActiveQueryFilter()).ToListAsync();

public static IEnumerable<Product> ActiveQueryFilter(this ICollection<Product> source)
{
    return source.Where(x => x.IsActive).AsEnumerable();
}

但我得到以下错误

System.InvalidOperationException:表达式“x.Products.ActiveQueryFilter()”在包含操作中无效。该表达式应表示属性访问:'t => t.MyProperty'。要定位在派生类型上声明的导航,请使用强制转换,例如't => ((Derived)t).MyProperty' 或 'as' 运算符,例如't => (t 作为派生).MyProperty'。集合导航访问可以通过组合 Where、OrderBy(Descending)、ThenBy(Descending)、Skip 或 Take 操作进行过滤。有关包含相关数据的更多信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393

我该如何解决?

【问题讨论】:

  • 逻辑原因:EF 不知道ActiveQueryFilter 做了什么。您可以从中返回任何IEnumerable&lt;Product&gt;。技术原因是 EF 知道如何翻译表达式,而不是像 ActiveQueryFilter 这样的自定义方法。相反,您可以将表达式 y =&gt; y.IsActive 存储在某个变量中,并将其提供给 Where 子句。
  • 来自link支持的操作有:Where、OrderBy、OrderByDescending、ThenBy、ThenByDescending、Skip 和 Take我猜这里不允许自定义扩展方法。跨度>

标签: c# asp.net-core entity-framework-core


【解决方案1】:

我不建议在 EF 查询中使用静态方法。 The documentation explains why

基本上它们会导致内存泄漏和意外行为

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2021-04-24
    • 2021-04-21
    • 2021-10-01
    • 2020-07-09
    • 2017-09-22
    • 1970-01-01
    • 2023-03-06
    相关资源
    最近更新 更多