简体   繁体   中英

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.

During filtering there are a lot of IF statements, which bodies has check if query is NULL. I need to avoid repeats, but the problem is that I can't add condition like query.And(exp) if query is 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 }. Not OR, but AND ALSO. So there are 0 projects as result.

            Expression<Func<Project, bool>> query = null, exp = null;

This is, how it works now in each IF statement:

            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.

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.

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".)

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