简体   繁体   中英

Error on Convert.ChangeType with Nullable<Int32>

I'm dynamically building a Lambda expression for a database query (using 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). When I try to construct a comparison Expression, I get a type error.

Car.Mileage is declared as follows:

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'.

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. ( Source )
  • I've tried Expression.Convert as described here and here , but haven't been able to get it to work.

Figure it out, largely by re-reading this post .

I had to use Expression.Convert with the Type of the property Expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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