在表达式树中使用可空类型 [英] Working with nullable types in Expression Trees

查看:200
本文介绍了在表达式树中使用可空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个扩展方法来使用字符串值动态过滤Linq到Entities结果。它工作正常,直到我使用它来过滤可空列。这是我的代码:

  public static IOrderedQueryable< T> OrderingHelperWhere< T>(此IQueryable< T>源,字符串columnName,对象值)
{
ParameterExpression table = Expression.Parameter(typeof(T),);
表达式列= Expression.PropertyOrField(table,columnName);
Expression where = Expression.GreaterThanOrEqual(column,Expression.Constant(value));
表达式lambda = Expression.Lambda(其中,new ParameterExpression [] {table});

类型[] exprArgTypes = {source.ElementType};

MethodCallExpression methodCall = Expression.Call(typeof(Queryable),
Where,
exprArgTypes,
source.Expression,
lambda);

return(IOrderedQueryable< T>)source.Provider.CreateQuery< T>(methodCall);
}

这是我如何使用它:

  var results =(从ctx.MyTable选择行中的行)
.OrderingHelperWhere(userId,5); // userId为可空的列

以下是使用这个可空表格列的异常:


没有为类型'System.Nullable`1 [System.Int32]'和'System.Int32'


定义二进制运算符GreaterThanOrEqual

我无法理解这一点。我应该怎么做?

解决方案

我必须使用Expression.Convert将值类型转换为列类型:

  Expression where = Expression.GreaterThanOrEqual(column,Expression.Convert(Expression.Constant(value),column.Type)); 


I have an extension method to dynamically filter Linq to Entities results using string values. It works fine until I use it to filter nullable columns. Here's my code:

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

Here's how I use it:

var results = (from row in ctx.MyTable select row)
              .OrderingHelperWhere("userId", 5);//userId is nullable column

Here's the exception I'm getting when I use this for nullable table columns:

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

I couldn't figured this out. What should I do?

解决方案

I had to convert the value type to the column type using Expression.Convert:

Expression where = Expression.GreaterThanOrEqual(column, Expression.Convert(Expression.Constant(value), column.Type));

这篇关于在表达式树中使用可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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