实体框架过滤器“Expression<Func<T, bool>>"
我正在尝试为实体框架列表创建一个过滤器方法并更好地理解Expression
I'm trying to create a filter method for Entity framework List and understand better the Expression<Func<...
我有一个这样的测试函数.
I have a Test Function like this.
public IQueryable<T> Filter<T>(IEnumerable<T> src, Expression<Func<T, bool>> pred)
{
return src.AsQueryable().Where(pred);
}
如果我这样做:
context.Table.Filter(e => e.ID < 500);
或者这个:
context.Table.Filter(e => e.SubTable.Where(et => et.ID < 500).Count() > 0 && e.ID < 500);
一切正常.
但是如果我这样做:
context.Table.Filter(e => e.SubTable.Filter(et => et.ID < 500).Count() > 0 && e.ID < 500);
或者这个:
context.Table.Where(e => e.SubTable.Filter(et => et.ID < 500).Count() > 0 && e.ID < 500);
我收到一个错误.LINQ to Entities 无法识别方法...Filter...
为什么它在一种情况下有效,而在加法器中无效?我应该在过滤器中更改什么才能使用相关表.我更喜欢远离其他外部库,因为我想要的是了解它的工作原理并能够在未来的任何场景中使用它.
Why it works in one case and not in the adder? What should I change in the Filter for it to work with related tables. I prefer to stay away from other external library's as what I want is to learn how it works and be able to use it in any scenario in future.
在前两种情况下,过滤器在数据库中正确运行.
In the first two cases the filter runs in the database correctly.
Jon 和 Tim 已经解释了为什么它不起作用.
Jon and Tim already explained why it doesn't work.
假设 Filter
中的过滤器代码不是微不足道的,您可以更改 Filter
使其返回一个 EF 可以翻译的表达式.
Assuming that the filter code inside Filter
is not trivial, you could change Filter
so that it returns an expression EF can translate.
假设您有以下代码:
context.Table.Where(x => x.Name.Length > 500);
您现在可以创建一个返回此表达式的方法:
You can now create a method the returns this expression:
Expression<Func<YourEntity, bool>> FilterByNameLength(int length)
{
return x => x.Name.Length > length;
}
用法如下:
context.Table.Where(FilterByNameLength(500));
您在FilterByNameLength
中构建的表达式可以是任意复杂的,只要您可以将其直接传递给Where
.
The expression you build inside FilterByNameLength
can be arbitrarily complex as long as you could pass it directly to Where
.