简体   繁体   中英

C# Expression Trees and is null

I am trying to create an expression tree to make a lambda that can be used in an EntityFramework Where clause. I need to check for null and am trying to use is null . So something like this:

    var param = Expression.Parameter(typeof(Customer), "data");
    var fieldExpression = Expression.Property(param, "Address");
    var nullTest = Expression.IsNull(fieldExpression);
    var lambda = Expression.Lambda(nullTest, param);
    var compiled = lambda.Compile() as Func<Customer, bool>;

    using dbContext = new TestDbContext();
    var customersWithNullAddress = dbContext.Customers.Where(compiled);

Here assuming that the dbContext has a DbSet<Customer> and Customer has a property called Address . The goal is to have this:

    var customersWithNullAddress = dbContext.Customers.Where(c => c.Address is null);

but I need to dynamically generate the predicate since it is coming from a user interface that allows the user to create the filter condition dynamically.

Of course this doesn't work because Expression.IsNull doesn't exist. I can't seem to find some mechanism to do this in expression trees. I guess I can do

    Expression.Equal(fieldExpression, Expression.Constant(null, typeof(Address))

But that doesn't seem like the recommended way to test null anymore, and I want to be sure it translates into the correct SQL as SELECT * FROM Customer WHERE Address is null

Anyone able to do this pattern matching in expression trees?

The is null operation in C# is syntactic sugar that was added long after LINQ expression trees were created. In regular code it compiles to the same IL code (for most cases at least) as == null , so there's not much incentive to add the syntax to expression trees at this point.

As to how it converts to SQL, == null has always converted to IS NULL in SQL since the good old LinqToSQL days. There may still be a few ways to get some SQL conversions to result in = NULL - which is of course always false - but you have to really try to invoke one of those.

So if you're just looking for assurance that the literal something == null will always translate to something IS NULL in SQL for EF (or LinqToSQL, or NHibernate, or Linq2DB, or...), you've got it. Too much code would break badly if it didn't work that way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM