如何将OData筛选器转换为LINQ表达式? [英] How to transform OData filter to a LINQ expression?
问题描述
我正在尝试从ODataQueryOptions
中提取过滤器表达式,以便可以在我的业务逻辑类中使用它.
I'm trying to extract the filter expression from ODataQueryOptions
so that I can use it in my business logic class.
public PageResult<Poco> Get(ODataQueryOptions odataQueryOptions)
{
Expression<Func<Poco, bool>> myExpression = ... // what do i do here?
var result = _myBusinessLogic.Search(myExpression);
return new PageResult<Poco>(result, null, null);
}
I took a look at the blog describing translating the query into HQL here and I think (at least I hope) that's an overkill for what I'm trying to do.
我基本上需要以Expression<Func<Poco, bool>>
形式获取过滤器表达式.我尝试使用ApplyTo()
玩游戏,但我不太明白.任何帮助表示赞赏.
I basically need to get the filter expression in the Expression<Func<Poco, bool>>
form. I tried playing with ApplyTo()
but I can't quite get it. Any help appreciated.
推荐答案
我们有一个FilterBinder类,它适合您的需求,但是内部很不幸.不过,您可以做一个简单的技巧来掌握$ filter表达式,
We have a FilterBinder class that suits your needs but is internal unfortunately. Nevertheless you could do a simple trick to get hold of the $filter expression,
public static class ODataQueryOptionsExtensions
{
public static Expression ToExpression<TElement>(this FilterQueryOption filter)
{
IQueryable queryable = Enumerable.Empty<TElement>().AsQueryable();
queryable = filter.ApplyTo(queryable, new ODataQuerySettings());
return queryable.Expression;
}
}
就您而言,您可以做到,
In your case, you can just do,
public PageResult<Poco> Get(ODataQueryOptions odataQueryOptions)
{
Expression<Func<Poco, bool>> myExpression = odataQueryOptions.Filter.ToExpression<Poco>();
var result = _myBusinessLogic.Search(myExpression);
return new PageResult<Poco>(result, null, null);
}
请注意,表达式包含的内容更像这样,
SOTests.Customer[].Where($it => conditional-expression)
.因此,您可能必须从lambda中提取该条件表达式.
Notice that the expression contains looks more like this,
SOTests.Customer[].Where($it => conditional-expression)
. So, you might have to extract that conditional expression from the lambda.
这篇关于如何将OData筛选器转换为LINQ表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!