Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform OData filter to a LINQ expression?

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.

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.

like image 443
boris Avatar asked May 08 '13 15:05

boris


1 Answers

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);
}

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.

like image 70
RaghuRam Nadiminti Avatar answered Nov 01 '22 05:11

RaghuRam Nadiminti