I am trying to create a generic Expression builder, which basically works fine as long as none the objects values is null.
My current code looks like this (StartsWith as an example):
case FilterOperationTypes.StartsWith:
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
PropertyInfo propertyInfo = typeof(T).GetProperty(field);
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(val, typeof(string));
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
Expression call = Expression.Call(m, mi, c);
return Expression.Lambda<Func<T, bool>>(call, e);
}
Let's assume field is the Property CustomerName. I understand that the actual final expression will be like:
e.CustomerName.StartsWith(val)
and if CustomerName is null it will, of course, fail to call the StartsWith Method, which is perfectly clear.
I have tried to do something like this:
case FilterOperationTypes.StartsWith:
{
ParameterExpression e = Expression.Parameter(typeof(T), "e");
PropertyInfo propertyInfo = typeof(T).GetProperty(field);
MemberExpression m = Expression.MakeMemberAccess(e, propertyInfo);
ConstantExpression c = Expression.Constant(val, typeof(string));
MethodInfo mi = typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
Expression call = Expression.IfThenElse(
Expression.Equal(m, Expression.Constant(null)),
Expression.Constant(null),
Expression.Call(m, mi, c));
//Expression.Call(m, mi, c);
return Expression.Lambda<Func<T, bool>>(call, e);
}
But this produces a Expression of type 'System.Void' cannot be used for return type 'System.Boolean' Exception.
I am a little bit lost as of now. Maybe you guys can push me in the right direction.
Thanks a lot!
Got it working now. Big thanks to Servy for pushing me in the right direction.
The Expression.Condition was exactly what I needed to achieve my goal. Since the actual object and the object's property can be null at run time I had to nest two Conditions:
In case of a null value I decided to use
to be sure to receive "false". I'm sure there is a nicer way to do this, but I could not think of one, yet.
The final Expression will look like this
As of now I am pretty happy with the solution, though I'll try to optimize it.
My current implementation and usage of the code looks like this. Maybe it helps one of you guys:
You're looking for
Expression.Condition
, rather thanIfThenElse
, which represents the conditional operator, rather than an if/else statement. The conditional operator resolves to a value, since it's an expression, not a statement.