繁体   English   中英

具有Nullable的Convert.ChangeType错误<Int32>

[英]Error on Convert.ChangeType with Nullable<Int32>

我正在为数据库查询动态构建Lambda表达式(使用LINQ)。 我有一个用户提供的字符串(例如“ 80”),我需要将该字符串与数据库实体对象(例如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);

这会导致错误:

未为类型'System.Nullable'1 [System.Int32]'和'System.Int32'定义Expression.Equal。

我尝试了几种方法来转换用户的参数,但没有成功。

  • Convert.ChangeType(constant,typeof(Car.Mileage))失败,因为Mileage的类型为RuntimePropertyInfo。 来源
  • 我已经按照此处此处所述尝试过Expression.Convert,但尚未使其正常工作。

找出答案,主要是通过重新阅读这篇文章

我必须将Expression.Convert与属性Expression的类型一起使用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM