应用表达式到LINQ Where子句 [英] Applying an Expression<> to a LINQ Where clause
问题描述
我正在编写自定义实体框架过滤器.我有一个ID列表和一个用户提供的表达式.
I'm writing a custom Entity Framework filter. I have a list of IDs, and a user-supplied expression.
protected IEnumerable<TColumn> FilterIds;
protected Expression<Func<T, IEnumerable<TColumn>, bool>> Filter;
现在我的问题是如何将Filter
表达式应用于Where()
子句?
Now my question is how do I apply the Filter
expression to a Where()
clause?
public virtual IQueryable<T> ApplyFilter(IQueryable<T> query)
{
if (FilterMode == FilterModeMatchAny && HasFilterIds)
{
// Whoops! Can't do this!
return query.Where(x => Filter(x, FilterIds));
}
return query;
推荐答案
使用此帖子中的Combine
方法您几乎需要的所有东西.从那里开始,您只需要将文字值转换成计算它的表达式(或者我猜可以更改答案的Combine
方法,这样中间值就不是从lambda计算出来的,而仅仅是任何表达式),并且然后调用该函数.
Using the Combine
method from this post does pretty much everything you need. From there you just need to turn the literal value into an expression that computes it (or I guess alter the Combine
method from that answer so that the intermediate value isn't computed from a lambda but rather is just any expression), and then call the function.
protected IEnumerable<TColumn> FilterIds;
protected Expression<Func<T, IEnumerable<TColumn>> FilterIdsExpression => _ => FilterIds;
protected Expression<Func<T, IEnumerable<TColumn>, bool>> Filter;
public virtual IQueryable<T> ApplyFilter(IQueryable<T> query)
{
if (FilterMode == FilterModeMatchAny && HasFilterIds)
{
return query.Where(FilterIdsExpression.Combine(Filter));
}
return query;
}
这篇关于应用表达式到LINQ Where子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!