LINQ to SQL: NOTing a prebuilt expression
- by ck
I'm building a library of functions for one of my core L2S classes, all of which return a bool to allow checking for certain situations.
Example:
Expression<Func<Account, bool>> IsSomethingX =
a => a.AccountSupplementary != null
&& a.AccountSupplementary.SomethingXFlag != null
&& a.AccountSupplementary.SomethingXFlag.Value;
Now to query where this is not true, I CAN'T do this:
var myAccounts= context.Accounts
.Where(!IsSomethingX); // does not compile
However, using the syntax from the PredicateBuilder class, I've come up with this:
public static IQueryable<T> WhereNot<T>(this IQueryable<T> items,
Expression<Func<T, bool>> expr1)
{
var invokedExpr = Expression.Invoke(expr1, expr1.Parameters.Cast<Expression>());
return items.Where(Expression.Lambda<Func<T, bool>>
(Expression.Not(invokedExpr), expr1.Parameters));
}
var myAccounts= context.Accounts
.WhereNot(IsSomethingX); // does compile
which actually produces the correct SQL.
Does this look like a good solution, and is there anything I need to be aware of that might cause me problems in future?