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

(The code below has been updated and fixed)

LinqPad has a dynamic OrderBy pattern. I want to just simply apply โ€œWhereโ€ and not โ€œ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 an exception: "InvalidOperationException: there is no method 'Where' on type 'System.Linq.Queryable' is compatible with the arguments provided.

Any help appreciated.

Greetings

+4
source share
2 answers
  • Use the lambda that John Skeet put. Perhaps he can also explain why ParameterExpression so painful to use and requires using an instance of the same instead of being customized by name :)

  • Change this line:

 Type[] exprArgTypes = { query.ElementType }; 

exprArgTypes are type parameters

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

As you can see, it has only one type parameter - TSource , which is Purchase . In fact, you made a call to the Where method with two type parameters, as shown below:

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

As soon as both of these corrections are in expression, they run without problems.

+2
source

Your creation of a lambda expression looks strange to me. You add one more parameter for no apparent reason. You also use Predicate<Purchase> instead of Func<Purchase, bool> . Try the following:

 LambdaExpression lambda = Expression.Lambda<Func<Purchase, bool>>( Expression.GreaterThan(member, Expression.Constant(100)), purchaseParam); 
+4
source

All Articles