How to detect IsNull / NotNull when building dynamic LINQ expressions?

asp.net-mvc c# entity-framework linq

Question

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.

1
15
9/13/2013 9:02:32 PM

Accepted Answer

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!

22
9/13/2013 9:40:01 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow