在表达式树中处理可为空的类型

21 浏览
0 Comments

在表达式树中处理可为空的类型

我有一个扩展方法,可以使用字符串值动态过滤Linq to Entities结果。它在过滤可空列时遇到了问题。以下是我的代码:

public static IOrderedQueryable OrderingHelperWhere(this IQueryable 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)source.Provider.CreateQuery(methodCall);
}

以下是我的用法:

var results = (from row in ctx.MyTable select row)
              .OrderingHelperWhere("userId", 5);//userId是可空列

使用这种方式过滤可空表列时,我遇到了以下异常:

The binary operator GreaterThanOrEqual is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'

我无法解决这个问题。我该怎么办?

0