简体   繁体   English

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

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

I'm dynamically building a Lambda expression for a database query (using LINQ). 我正在为数据库查询动态构建Lambda表达式(使用LINQ)。 I have a user provided string (eg "80") that I need to compare against a field in my database entity object (eg Car.Mileage). 我有一个用户提供的字符串(例如“ 80”),我需要将该字符串与数据库实体对象(例如Car.Mileage)中的字段进行比较。 When I try to construct a comparison Expression, I get a type error. 当我尝试构造比较表达式时,出现类型错误。

Car.Mileage is declared as follows: Car.Mileage声明如下:

public Nullable<int> Mileage

I'm building my query this way: 我以这种方式建立查询:

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

This results in an error: 这会导致错误:

Expression.Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'. 未为类型'System.Nullable'1 [System.Int32]'和'System.Int32'定义Expression.Equal。

I've tried a few approaches to converting the user's argument, without much success. 我尝试了几种方法来转换用户的参数,但没有成功。

  • Convert.ChangeType(constant, typeof(Car.Mileage)) failed because Mileage's type is RuntimePropertyInfo. Convert.ChangeType(constant,typeof(Car.Mileage))失败,因为Mileage的类型为RuntimePropertyInfo。 ( Source ) 来源
  • I've tried Expression.Convert as described here and here , but haven't been able to get it to work. 我已经按照此处此处所述尝试过Expression.Convert,但尚未使其正常工作。

Figure it out, largely by re-reading this post . 找出答案,主要是通过重新阅读这篇文章

I had to use Expression.Convert with the Type of the property Expression: 我必须将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