I', trying to refactor some linq-2-sql magic and there is something I apperantly cannot wrap my head around. The code uses this predicate builder
public static class PredicateBuilder {
public static Expression<Func<T, bool>> True<T>() {
return f => true;
}
public static Expression<Func<T, bool>> False<T>() {
return f => false;
}
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2) {
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2) {
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
Used in the folloowing way:
predicate =
predicate.And(
f =>
f.Created != null
? args.Dato1.Date < f.Created.Value.Date &&
f.Created.Value.Date < args.Dato2.Date
: false);
A lot.
So I was thinking maybe use a more descriptive name and less lines in the following way:
private Expression<Func<DAL.Faktura, bool>> beforeInclusiveExpression(Func<DAL.Faktura, DateTime?> getDateTime, DateTime date) {
return f => getDateTime(f).HasValue && getDateTime(f).Value.Date <= date.Date;
}
And then build the predicate in the following way:
predicate =
predicate
.And(beforeInclusiveExpression(f => f.Created, d.Dato2)
.And(afterInclusiveExpression(f => f.Created, d.Dato1);
But that does not work, it just throws the following error Method 'System.Object DynamicInvoke(System.Object[])' has no supported translation to SQL.. I understand that it's because the linq-2-sql provider does not know what to do with the lambda, but how can I translate it to something that will enable me to refactor to something more maintainable.
Expression. I forgot to show the code where I use it, please see the edit where it is included.