Expression Trees and Nullable Types

2020-02-25 01:17发布

问题:

I've been playing around with Expression Trees. I have the following simple method that performs a query by dynamically creating an Expression Tree. ItemType is a nullable int in the database, and also in the EF entity class. For some reason though the query throws the error of

Unhandled Exception: System.InvalidOperationException: The binary operator Equal is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.

I don't think I'm asking EF to convert anything. I've got my parameter defined as int?, which is what I thought it should be.

Note, I've looked at this

Working with nullable types in Expression Trees

But this guy is trying to pass in his nullable int value typed as object, which EF I guess has problems with. I'm actually declaring this as the right type ab initio.

   public void GetResultCollection<T>() {
        MyEntities db = new MyEntities();
        var result = db.CreateQuery<T>(String.Format("[{0}]", typeof(T).Name + "s"));

        int? ItemTypeValue = 1;

        var param = Expression.Parameter(typeof(T));

        var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "ItemType"),
                Expression.Constant(ItemTypeValue)),
            param);

        var list = result.Where(lambda).ToList();
    }

EDIT

I've also tried ItemTypeValue.Value - same error

回答1:

I think you need to convert it

var right = Expression.Constant(ItemTypeValue , typeof(int?))
....

 var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "ItemType"),
                right),
            param);