[英]Is there default value for expression, which doesn't influence on it?
I have a filter by some projects in my app. 我在我的应用程序中按某些项目进行了筛选。 It works using Expression query, which is NULL at the start.
它使用表达式查询工作,开头是NULL。
During filtering there are a lot of IF statements, which bodies has check if query is NULL. 在过滤期间,有很多IF语句,这些语句检查查询是否为NULL。 I need to avoid repeats, but the problem is that I can't add condition like query.And(exp) if query is NULL.
我需要避免重复,但是问题是我无法添加条件,例如query.And(exp)如果query为NULL。
So before adding condition - the query variable must have value. 因此,在添加条件之前-查询变量必须具有值。 My first idea is to add condition and remove it before applying filter, but I couldn't remove that from the body, because it's not a string and I haven't found such methods for it.
我的第一个想法是添加条件并在应用过滤器之前将其删除,但是我无法从主体中将其删除,因为它不是字符串,并且我还没有找到这种方法。 Then I've tried to add condition, which tells filter to take projects with ID equal to MAXINT, but that doesn't work, because query body looks like { p => p.ID == 2147483647 And also }.
然后,我尝试添加条件,该条件告诉过滤器接受ID等于MAXINT的项目,但这不起作用,因为查询主体看起来像{p => p.ID == 2147483647还有}。 Not OR, but AND ALSO.
不是OR,而是AND。 So there are 0 projects as result.
因此,有0个项目。
Expression<Func<Project, bool>> query = null, exp = null;
This is, how it works now in each IF statement: 这就是现在每个IF语句中的工作方式:
if (filter.ViewSomeProjects)
{
exp = p => (some conditions);
query = query != null ? query.And(exp) : exp;
}
This is, how I want it to work: 这就是我希望它如何工作:
if (filter.ViewSomeProjects)
{
query.And(some conditions);
}
So I can't do it like I want, while query is NULL at the beginning. 因此,我无法做到自己想要的,而查询开始时为NULL。
My questions are: Is there any way to delete part of expression body? 我的问题是:有什么方法可以删除表达主体的一部分? Is it possible to add useless condition to the expression, which won't influence on result?
是否可以在表达式中添加无用的条件,而不会影响结果?
Predicate Builder by Joe Albahari has a True
and False
that you can use as the starting point. 谓词生成器乔阿尔巴哈利有
True
和False
,你可以作为起点使用。
public static Expression<Func<T, bool>> True<T> () { return f => true; }
public static Expression<Func<T, bool>> False<T> () { return f => false; }
If you start from one of these, you can then build up your query depending on what the default behaviour is (generally True works fine when adding restrictions to a default of "all results".) 如果您从其中之一开始,则可以根据默认行为是什么来建立查询(通常,将限制添加到默认值“所有结果”时,True可以正常工作。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.