带有Nullable <int32> </int32>的Convert.ChangeType出错

时间:2015-01-12 15:42:32

标签: c# .net linq entity-framework

我正在为数据库查询动态构建Lambda表达式(使用LINQ)。我有一个用户提供的字符串(例如&#34; 80&#34;),我需要与我的数据库实体对象(例如Car.Mileage)中的字段进行比较。当我尝试构建比较表达式时,我得到一个类型错误。

Car.Mileage声明如下:

public Nullable<int> Mileage

我以这种方式构建我的查询:

Nullable<int> userProvided = Int32.parse(arg);
Expression constant = Expression.Constant(userProvided);
Expression property = Expression.Property(car, "Mileage");
Expression exp = Expression.Equal(property, constant);

这会导致错误:

  

没有为类型定义Expression.Equal   &#39; System.Nullable`1 [System.Int32]&#39;和&#39; System.Int32&#39;。

我尝试了一些方法来转换用户的论点,却没有取得多大成功。

  • Convert.ChangeType(常量,typeof(Car.Mileage))失败,因为“前程万里”的类型是RuntimePropertyInfo。 (Source
  • 我已经按照herehere所述尝试了Expression.Convert,但是还没有能够让它发挥作用。

1 个答案:

答案 0 :(得分:0)

弄清楚,主要是重新阅读this post

我必须使用Expression.Convert和属性Expression的类型:

Expression.Equal(property, Expression.Convert(constant, ((MemberExpression)property).Type));