![](/img/trans.png)
[英]Dynamic lambda expression doesn't work in LINQ to EF Where function
[英]Dynamic Linq Where with Lambda Expression generates Error
我有一个动态 Linq 查询
public static IQueryable<T> WhereHelper<T>(this IQueryable<T> source, string property, string propertyValue) where T : class
{
//STEP 1: Verify the property is valid
var searchProperty = typeof(T).GetProperty(property);
//STEP 2: Create the OrderBy property selector
var parameter = Expression.Parameter(typeof(T), "o");
MemberExpression member = Expression.Property(parameter, property);
MethodInfo method = typeof(string).GetMethod("Contains", new[] { typeof(string) });
ConstantExpression constant = Expression.Constant(propertyValue);
MethodCallExpression queryExpr = Expression.Call(member, method, constant);
ParameterExpression pe = Expression.Parameter(typeof(string), property);
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<string, bool>>(queryExpr, new ParameterExpression[] { pe }));
return source.Provider.CreateQuery<T>(whereCallExpression);
}
此函数会生成如下错误:
类型“System.Linq.Queryable”上的任何泛型方法“Where”都与提供的类型参数和参数不兼容。 如果方法是非通用的,则不应提供类型参数。
关于错误的想法,谢谢
您需要传递Func<T, bool>
因为Where
方法的谓词是一个函数来测试每个元素的条件和输入元素的类型是T
而输出是bool
。
最后,在创建 lambda 表达式时,传递在queryExpr
使用的相同参数,否则会引发错误变量未找到。 因此,它不是pe
,而是parameter
。
MethodCallExpression whereCallExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { source.ElementType },
source.Expression,
Expression.Lambda<Func<T, bool>>(
queryExpr,
new ParameterExpression[] { parameter }
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.