0
votes

I'm dynamically building a Lambda expression for a database query (using LINQ). I have a user provided string (e.g. "80") that I need to compare against a field in my database entity object (e.g. 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.
1
What's the point? Int32.Parse() does not generate a nullable.Hans Passant
@hans It does not generate a nullable, but Expression.Equal() complains if one parameter is nullable and the other is not.T.D. Smith

1 Answers

0
votes

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