I am trying to build an expression tree programmatically.
I have in my input, a list of condition classes which have the following form:
public class Filter
{
public string field { get; set; }
public string operator { get; set; }
public string value { get; set; }
}
When I build the Expression
object I create an Expression
for every condition in the following way
foreach ( Filter sf in rules ) {
Expression ex = sf.ToExpression( query );
if ( mainExpression == null ) {
mainExpression = ex;
}
else {
if ( logicalCondition == "AND" ) {
mainExpression = Expression.And( mainExpression, ex );
}
else if ( logicalCondition == "OR" ) {
mainExpression = Expression.Or( mainExpression, ex );
}
}
}
The Filter.ToExpression() method is implemented like this
public override Expression ToExpression( IQueryable query ) {
ParameterExpression parameter = Expression.Parameter( query.ElementType, "p" );
MemberExpression memberAccess = null;
foreach ( var property in field.Split( '.' ) )
memberAccess = MemberExpression.Property( memberAccess ?? ( parameter as Expression ), property );
ConstantExpression filter = Expression.Constant( Convert.ChangeType( value, memberAccess.Type ) );
WhereOperation condition = (WhereOperation)StringEnum.Parse( typeof( WhereOperation ), operator );
LambdaExpression lambda = BuildLambdaExpression( memberAccess, filter, parameter, condition, value );
return lambda;
}
Everything works when I have a single condition but when I try to combine expressions using one of the And
, Or
, AndAlso
, OrElse
static methods I receive an InvalidOperationException
that says:
The binary operator Or is not defined for the types 'System.Func
2[MyObject,System.Boolean]' and 'System.Func
2[MyObject,System.Boolean]'.
I am getting a little bit confused. Can somebody better explain the reasons of the exception and suggest a solution?
Thanks very much!