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
Expression Trees represent code as a structure that you can examine, modify, or execute. These tools give you the power to manipulate code during run time. You can write code that examines running algorithms, or injects new capabilities.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.
Expression trees allow you to build code dynamically at runtime instead of statically typing it in the IDE and using a compiler. They are well explained in the documentation.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With