Search code examples
c#lambdaexpression-treesc#-7.0

Create Where Clause Dynamically For Byte? Field


Related To: Create a Lambda Expression With 3 conditions

Exactly similar to above topic I wrote this Expression:

var body = Expression.AndAlso(
Expression.Equal(
    Expression.PropertyOrField(param, "Year"),
    Expression.Constant(year)
    ),
    Expression.AndAlso(
        Expression.Equal(
            Expression.PropertyOrField(param, "CityCode"),
            Expression.Constant(cityCode)
        ),
        Expression.Equal(
            Expression.PropertyOrField(param, "Status"),
            Expression.Constant(50)
        )
    )
);

the only different is in my new table Status is tinyint null or (byte?) in C#. When I run the code I got this error:

The binary operator Equal is not defined for the types 'System.Nullable`1[System.Byte]' and 'System.Byte'

so I change Expression.Constant(50) to Expression.Constant((byte?)50) and again got the same error. Where is my mistake?

Thanks


Update 1)

I tried this: Expression.Constant(50, typeof(byte?)); but I got this error:

Argument types do not match


Solution

  • Almost as Evan said:

    Expression.Constant((byte?)50, typeof(byte?))