Build IQueryable.Any with Expression Trees for LINQ queries

后端 未结 1 2167
情深已故
情深已故 2021-02-20 07:02

I\'m building a SQL \"WHERE\" clause dynamically using the System.Linq.Expressions.Expression class. It works well for simple clauses, e.g. to add \"PhaseCode = X\" clause, I do

相关标签:
1条回答
  • 2021-02-20 07:44

    Calling an extension method, like Enumerable.Any or Queryable.Any, is simply a static method call on the sequence and the lambda expression you created for the WHERE clause. You can use Expression.Call to do this:

    // for Enumerable.Any<T>(IEnumerable<T>,Predicate<T>)
    var overload = typeof(Enumerable).GetMethods("Any")
                                     .Single(mi => mi.GetParameters().Count() == 2);
    var call = Expression.Call(
        overload,
        Expression.PropertyOrField(projParam, "GroupsAssigned"),
        anyLambda);      
    

    For Queryable.Any<T>, you'll need to roll this up into a method:

    static Expression BuildAny<TSource>(Expression<Func<TSource, bool>> predicate)
    {
        var overload = typeof(Queryable).GetMethods("Any")
                                  .Single(mi => mi.GetParameters().Count() == 2);
        var call = Expression.Call(
            overload,
            Expression.PropertyOrField(projParam, "GroupsAssigned"),
            predicate);   
    
        return call;
    }
    

    Although this seems odd that you're unable to do this through a normal query.

    0 讨论(0)
提交回复
热议问题