Search code examples
c#linqlambda

Property is not defined for type 'System.Nullable`1[System.Double] when using Expressions


I have an expression that I am trying to build using a parameter and its value. The value within the parameter is a member expression object.

//targetFieldExp - MemberExpression
//targetFieldExp.Type - 'System.Nullable`1[System.Double]'"
//targetFieldExp.Member.Name - 'quantity'

var param = Expression.Parameter(targetFieldExp.Type, "blah");
var prop = Expression.Property(param, targetFieldExp.Member.Name); //error occurs here
var myConstant = Expression.Constant((double?)5);
return Expression.Lambda<Func<T, bool>>(Expression.Equal(prop, myConstant));

My issue is the moment I try to create the Expression Property I get "Property is not defined for type 'System.Nullable`1[System.Double] when using Expressions"

I have also tried the statement below with no luck:

Expression.Property(param, (PropertyInfo)targetFieldExp.Member)

Solution

  • MemberExpression.Type will return the type of the property:

    Gets the static type of the expression that this Expression represents. (Inherited from Expression)

    if you need the type declaring it use MemberExpression.Member.DeclaringType;:

    var memberDeclaringType = targetFieldExp.Member.DeclaringType;
    var param = Expression.Parameter(memberDeclaringType, "blah");
    var prop = Expression.Property(param, targetFieldExp.Member as PropertyInfo); // todo - validate is not null