InvalidOperationException: No method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied arguments

天涯浪子 提交于 2019-12-04 03:43:53

问题


(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


回答1:


  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.




回答2:


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


来源:https://stackoverflow.com/questions/3423270/invalidoperationexception-no-method-where-on-type-system-linq-queryable-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!