LINQ to SQL: NOTing a prebuilt expression

Posted by ck on Stack Overflow See other posts from Stack Overflow or by ck
Published on 2010-05-24T15:41:09Z Indexed on 2010/05/24 16:41 UTC
Read the original article Hit count: 171

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about linq-to-sql