【发布时间】: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<Product>。技术原因是 EF 知道如何翻译表达式,而不是像ActiveQueryFilter这样的自定义方法。相反,您可以将表达式y => y.IsActive存储在某个变量中,并将其提供给Where子句。 -
来自link:支持的操作有:Where、OrderBy、OrderByDescending、ThenBy、ThenByDescending、Skip 和 Take我猜这里不允许自定义扩展方法。跨度>
标签: c# asp.net-core entity-framework-core