tags:

views:

90

answers:

3

Hi,

(Code below has been updated and worked properly)

There is dynamic OrderBy sample from LinqPad. What I want to do is just simply apply 'Where' rather than 'OrderBy' for this sample. Here is my code:

    IQueryable query =            
    from p in Purchases
    //where p.Price > 100
    select p;

string propToWhere = "Price"; 

ParameterExpression purchaseParam = Expression.Parameter (typeof (Purchase), "p");
MemberExpression member = Expression.PropertyOrField (purchaseParam, propToWhere);

Expression<Func<Purchase, bool>> lambda = p => p.Price < 100;
lambda.ToString().Dump ("lambda.ToString");


//Type[] exprArgTypes = { query.ElementType, lambda.Body.Type };
Type[] exprArgTypes = { query.ElementType };

MethodCallExpression methodCall =
    Expression.Call (typeof (Queryable), "Where", exprArgTypes, query.Expression, lambda);

IQueryable q = query.Provider.CreateQuery (methodCall);
q.Dump();
q.Expression.ToString().Dump("q.Expression");

This code gets exception: "InvalidOperationException: No method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied arguments."

Any help is appraicated.

Cheers

+2  A: 

Your lambda expression creation looks odd to me. You're adding another parameter for no obvious reason. You're also using Predicate<Purchase> instead of Func<Purchase, bool>. Try this:

LambdaExpression lambda = Expression.Lambda<Func<Purchase, bool>>(
                    Expression.GreaterThan(member, Expression.Constant(100)), 
                    purchaseParam);
Jon Skeet
Hi Jon, thanks for your reply. The expression you provide complains"The binary operator GreaterThan is not defined for the types 'System.Decimal' and 'System.Int32'."
Zalan
Ah. You hadn't made it clear that `Price` is a decimal. The simplest solution is to change the 100 to 100m, I suspect.
Jon Skeet
+1  A: 
  1. Use the lambda that Jon Skeet supplied. Perhaps he can also explain why ParameterExpression is so painful to use and requires using the same instance, instead of being able to be matched by name :)

  2. Modify this line:

Type[] exprArgTypes = { query.ElementType };

exprArgTypes is type parameters to

IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate).

As you can see it only has one type parameter - TSource, which is Purchase. What you were doing, effectively, was calling Where method with two type parameters like below:

IQueryable<Purchase> Where<Purchase, bool>(this IQueryable<Purchase> source, Expression<Func<Purchase, bool>> predicate)

Once both of those fixes are in the expression runs with no problem.

Igor Zevaka
A: 

Thanks Igor Zevaka. It works now. I've updated my above post with the correct code.

Zalan