如何构建动态LINQ前pressions当检测ISNULL / NOTNULL? [英] How to detect IsNull / NotNull when building dynamic LINQ expressions?
问题描述
我构建动态LINQ前pression即后来评估。因此,举例来说,如果我想知道如果某些属性等于某个值我做的:
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))
不过,我似乎无法找到一种方法来检测,如果val为NULL或NOT NULL。有人可以推荐给我该怎么做?我试过这样:
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.
推荐答案
OK,原来@拉斐尔Althaus先生是正确的 - 问题是在我建立predicate一部分。如此看来这其实也给你空检查:
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));
这意味着你可以使用Where条件动态地在诸如查询:
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);
感谢您的帮助!
这篇关于如何构建动态LINQ前pressions当检测ISNULL / NOTNULL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!