First, use our own predicate builder:
public static class PredicateBuilder
{
public static System.Linq.Expressions.Expression<Func<T, bool>> Null<T>() { return null; }
public static System.Linq.Expressions.Expression<Func<T, bool>> Or<T>(this System.Linq.Expressions.Expression<Func<T, bool>> expr1,
System.Linq.Expressions.Expression<Func<T, bool>> expr2)
{
if(expr1 == null)
{
return expr2;
}
ExpressionReplacer replacer = new ExpressionReplacer(CreateFromToReplaceSet(expr2.Parameters, expr1.Parameters), null, null, null, null);
LambdaExpression rightExpression = (LambdaExpression)replacer.HandleExpression(expr2);
return System.Linq.Expressions.Expression.Lambda<Func<T, bool>>
(System.Linq.Expressions.Expression.OrElse(expr1.Body, rightExpression.Body), expr1.Parameters);
}
public static System.Linq.Expressions.Expression<Func<T, bool>> And<T>(this System.Linq.Expressions.Expression<Func<T, bool>> expr1,
System.Linq.Expressions.Expression<Func<T, bool>> expr2)
{
if(expr1 == null)
{
return expr2;
}
ExpressionReplacer replacer = new ExpressionReplacer(CreateFromToReplaceSet(expr2.Parameters, expr1.Parameters), null, null, null, null);
LambdaExpression rightExpression = (LambdaExpression)replacer.HandleExpression(expr2);
return System.Linq.Expressions.Expression.Lambda<Func<T, bool>>
(System.Linq.Expressions.Expression.AndAlso(expr1.Body, rightExpression.Body), expr1.Parameters);
}
private static Dictionary<LinqExpression, LinqExpression> CreateFromToReplaceSet(IList<ParameterExpression> from,
IList<ParameterExpression> to)
{
Dictionary<LinqExpression, LinqExpression> toReturn = new Dictionary<LinqExpression, LinqExpression>();
for(int i = 0; i < from.Count; i++)
{
toReturn.Add(from[i], to[i]);
}
return toReturn;
}
}
see this thread for more information and usage:
http://www.llblgen.com/tinyforum/Messages.aspx?ThreadID=14144
This way, you can build dynamic predicates using Linq which are merged into the expression tree and which are used for the final query on the DB.