【发布时间】:2013-01-22 09:47:47
【问题描述】:
我正在尝试使用表达式树创建动态查询以匹配以下语句:
var items = data.Where(i => i.CoverageType == 2).Select(i => i.LimitSelected);
我可以创建 where 方法并从中获取结果;但是,我无法创建 select 方法。
这是我的 where 方法:
var parm = Expression.Parameter(typeof(BaseClassData), "baseCoverage");
var queryData = data.AsQueryable();
var left = Expression.Property(parm, "CoverageType");
var right = Expression.Constant(2m);
var e1 = Expression.Equal(left, right);
var whereMethod = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { queryData.ElementType },
queryData.Expression,
Expression.Lambda<Func<BaseClassData, bool>>(e1, new ParameterExpression[] { parm }));
这就是我使用的 select 方法:
var selectParm = Expression.Property(parm, "LimitSelected");
var selectMethod = Expression.Call(
typeof(Enumerable),
"Select",
new Type[]{typeof(BaseClassData), typeof(decimal)},
whereMethod,
Expression.Lambda<Func<BaseClassData, decimal>>(selectParm, new ParameterExpression[]{ parm})
);
运行代码时出现此错误:
类型“System.Linq.Enumerable”上没有通用方法“Select”与提供的类型参数和参数兼容。如果方法是非泛型的,则不应提供类型参数。
我也尝试将 Enumerable 更改为 Queryable,但我得到了同样的错误。
【问题讨论】:
-
Select和Where采用两个通用参数。 -
你的意思是在ParameterExpression数组中吗?我问是因为 were 语句在编码时可以正常工作。如果我只使用 where 方法创建查询,一切正常。当我尝试将 select 方法添加到表达式树时。
-
我将 typeof(BaseClassData) 添加到 selectMethod 的类型数组中,它可以工作。
-
如果您自己解决了,那么您应该添加一个答案并将其标记为解决方案。
标签: c# linq exception-handling expression-trees