Reputation: 7800
I'm trying to build a dynamic query whit a condition on an emum
enumField & enumValue == enumValue
for this, during the analysis the following is called
Expression GenerateBitWiseAnd(Expression left, Expression right) {
return Expression.And(left, right);
}
this throws an exception
And binary operator is not defined for `EnumType` and `EnumType`.
The equality operator runs well
Expression GenerateEqual(Expression left, Expression right) {
return Expression.Equal(left, right);
}
But I can't figure how to handle a [Flags] without the And bits operator.
The question is: from here how to dynamically forge my query to check my enum.
My application is targeting .Net 4
Upvotes: 2
Views: 415
Reputation: 31198
You'll need to convert the Enum
to its underlying type before you can operate on it:
Expression GenerateBitWiseAnd(Expression left, Expression right)
{
if (left.Type.IsEnum)
{
var enumType = left.Type;
var compareType = Enum.GetUnderlyingType(enumType);
var enumField = Expression.Convert(left, compareType);
var enumValue = Expression.Convert(right, compareType);
var and = Expression.And(enumField, enumValue);
return Expression.Convert(and, enumType);
}
return Expression.And(left, right);
}
Upvotes: 1