views:

48

answers:

2

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?

+3  A: 
var compiled = IsSomethingX.Compile();
var myAccounts = context.Accounts.Where(x => !compiled(x));
Stephan
Thanks for the alternative.
ck
+4  A: 

I wrote some test code using your WhereNot extension method and it looks good. @Stephan's solution also works, but I'd go for the readability of the extension method.

Jeff Schumacher
+1, the solution outlined is fine and easier to use.
Johannes Rudolph