mercredi 17 mai 2017

ArgumentException when calling Expression.GreaterThanOrEqual via Expression.Call

I get different behaviours when calling Expression.GreaterThanOrEqual dynamically or directly.

MethodInfo _greaterThanOrEqual = typeof(Expression).GetMethod("GreaterThanOrEqual",
                    new[] {typeof(Expression), typeof(Expression)});

Expression valueExpr = Expression.Convert(Expression.Constant(value), property.Type);

// Dynamic Call
expressionBody = Expression.Call(null, methodInfo, property, valueExpr);
// Direct Call
expressionBody = Expression.GreaterThanOrEqual(property, valueExpr);

return Expression.Lambda<Func<T, bool>>(expressionBody, Param);

I took the code out of context for simplicity reasons. The returned Lambda is later used within a where method of a Queryable. The direct call works fine and gives expected results. (Obviously I don't call them one after another). The dynamic call however throws a System.ArgumentException saying that DateTime?cannot be used as a parameter for the BinaryExpression GreaterThanOrEqual. That's actually the reason why I convert the value previously, which is also necessary for the direct call.

Whats the difference here? How could I get the dynamic call to work?





Aucun commentaire:

Enregistrer un commentaire