我有一个扩展方法,使用字符串值动态过滤Linq到实体结果.它工作正常,直到我用它来过滤可空列.这是我的代码:
public static IOrderedQueryable<T> OrderingHelperWhere<T>(this IQueryable<T> source, string columnName, object value)
{
ParameterExpression table = Expression.Parameter(typeof(T), "");
Expression column = Expression.PropertyOrField(table, columnName);
Expression where = Expression.GreaterThanOrEqual(column, Expression.Constant(value));
Expression lambda = Expression.Lambda(where, new ParameterExpression[] { table });
Type[] exprArgTypes = { source.ElementType };
MethodCallExpression methodCall = Expression.Call(typeof(Queryable),
"Where",
exprArgTypes,
source.Expression,
lambda);
return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(methodCall);
}
Run Code Online (Sandbox Code Playgroud)
这是我如何使用它:
var results = (from row in ctx.MyTable select row)
.OrderingHelperWhere("userId", 5);//userId is nullable column
Run Code Online (Sandbox Code Playgroud)
这是我在将可用于可空表列时使用的异常:
没有为类型'System.Nullable`1 [System.Int32]'和'System.Int32'定义二元运算符GreaterThanOrEqual
我无法理解这一点.我该怎么办?
从5分钟前我提出的这个问题来看,很明显以下代码抛出异常,说明了这一点
未处理的异常:System.InvalidOperationException:没有为类型'System.Nullable`1 [System.Int32]'和'System.Int32'定义二进制运算符Equal.
码
public static void GetResultCollection<T>() {
AccrualTrackingEntities db = new AccrualTrackingEntities();
var result = db.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name + "s"));
int? ItemTypeValue = 1;
var param = Expression.Parameter(typeof(T));
var lambda = Expression.Lambda<Func<T, bool>>(
Expression.Equal(
Expression.Property(param, "ProcInstId"),
Expression.Constant(ItemTypeValue)),
param);
var list = result.Where(lambda).ToList();
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码具有明确列出的类型Expression.Constant确实有效
class Program {
public static void GetResultCollection<T>() {
AccrualTrackingEntities db = new AccrualTrackingEntities();
var result = db.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name + "s"));
int? ItemTypeValue = 1;
var param = Expression.Parameter(typeof(T));
var lambda = …Run Code Online (Sandbox Code Playgroud)