Nullable Types and Expression Trees

c# entity-framework expression-trees

Question

Expression Trees are a toy I've been experimenting with. The straightforward way I have available here executes a query by dynamically generating an Expression Tree. The database has an int named ItemType with the value and in the EF entity class as well.. However, for some reason, the query returns an error saying

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 believe I am requesting any conversions from EF. I've defined my parameter asint? which is how I expected it to be.

Remember, I looked at this

Using nullable types with Expression Trees

However, this person is attempting to input a nullable int value that is typed as an object, which EF, I assume, has issues with. In reality, I'm claiming that this is the correct kind at first.

   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

Also, I have attemptedItemTypeValue.Value The similar mistake

1
18
5/23/2017 11:54:26 AM

Accepted Answer

I believe you should convert it.

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

 var lambda = Expression.Lambda<Func<T, bool>>(
            Expression.Equal(
                Expression.Property(param, "ItemType"),
                right),
            param);
25
2/21/2011 2:44:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow