InvalidOperationException:类型'System.Linq.Queryable'上的方法'Where'与提供的参数不兼容 [英] InvalidOperationException: No method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied arguments

查看:70
本文介绍了InvalidOperationException:类型'System.Linq.Queryable'上的方法'Where'与提供的参数不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(下面的代码已更新,并且可以正常工作)

(Code below has been updated and worked properly)

有一个来自LinqPad的动态OrderBy示例.我想做的只是对该示例应用"Where"而不是"OrderBy".这是我的代码:

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

此代码获取异常: "InvalidOperationException:类型'System.Linq.Queryable'上的任何方法'Where'与提供的参数都不兼容."

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

任何帮助都会得到评价.

Any help is appraicated.

欢呼

推荐答案

  1. 使用Jon Skeet提供的lambda.也许他还可以解释为什么ParameterExpression使用起来如此痛苦并且需要使用 same 实例,而不是能够通过名称进行匹配的原因:)

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

修改此行:

Type[] exprArgTypes = { query.ElementType };

exprArgTypes

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

如您所见,它只有一个类型参数-TSource,即Purchase.有效地,您正在做的是使用如下两个类型参数调用Where方法:

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.

这篇关于InvalidOperationException:类型'System.Linq.Queryable'上的方法'Where'与提供的参数不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆