17

I'm building dynamic LINQ expression that is later evaluated. So for example if I want to know if certain property is equal to some value I do:

// MemberExpression property;
// int? val;
Expression.Equal(property, Expression.Constant(val))

However, I can't seem to find a way to detect if val Is Null or NOT Null. Can somebody recommend to me how to do that? I've tried this:

Expression.Equal(property, Expression.Constant(null, property.Type));

but obviously, that won't work.

nikib3ro
  • 20,366
  • 24
  • 120
  • 181
  • 1
    Once option would be to pass in a string like `Property != null` and compile/invoke that dynamically. I'm assuming this is part of a bigger Expression Tree? If so, how is it being generated? – Arian Motamedi Sep 13 '13 at 21:10
  • 2
    could you give a little bit more context ? Rather hard to understand where's your real problem... Think you should do something like `Expression.Constant(val, )` where theTypeofVal could be a nullable type, but as we don't know where val is coming from... – Raphaël Althaus Sep 13 '13 at 21:10
  • `!val.HasValue` if it's a nullable value type? – ps2goat Sep 13 '13 at 21:27

1 Answers1

25

OK, turns out @Raphaël Althaus was right - the problem is in part where I build predicate. So it seems this actually does give you null check:

Expression.Equal(property, Expression.Constant(null, property.Type));

Meaning that you can apply Where condition dynamically on query like:

// IQueryable<T> query;
// var arg = Expression.Parameter(typeof(T), "p");

var exp = Expression.Equal(property, Expression.Constant(null, property.Type));
          // for NOT NULL use Expression.NotEqual
var predicate = Expression.Lambda<Func<T, bool>>(exp, arg);
return query.Where(predicate);

Thanks for the help!

nikib3ro
  • 20,366
  • 24
  • 120
  • 181
  • **This solution does not check for null it invokes `operator ==`!** This might or might not be the same. If you really want to check for null **you must use `Expression.ReferenceEqual`** rather than 'Expression.Equal`. – Marcel Jul 16 '21 at 07:52