How to bind alternative conditions in where where in Entity Framework

I am trying to rewrite the following query as separate statements:

var sql = Repository.Products.AsQueryable(); sql = sql.Where(x => x.Name == "aaaaa" || x.Name == "bbbbb"); 

If I do it like this:

 sql = sql.Where(x => x.Name == "aaaaa"); sql = sql.Where(x => x.Name == "bbbbb"); 

then the received request is equal to:

 sql = sql.Where(x => x.Name == "aaaaa" && x.Name == "bbbbb"); 

Any ideas how to do this correctly?

+4
source share
2 answers

The right way ... is this . I mean, you could write it like

 sql.Where(x => x.Name == "aaaaa").Concat(sql.Where(x => x.Name == "bbbbb")); 

but slower, disordered, and look weirder. I do not know what you are looking for, because the way you posted is the right way to do this.

However , it seems you want to dynamically build the expression (judging by your comment). If yes, then you are looking for PredicateBuilder :

 var predicate = PredicateBuilder.False<YourType>(); var search = new[] {"aaaaa", "bbbbb"}; foreach (string y in search) { string name = y; predicate = predicate.Or(x => x.Name == name); } sql = sql.Where(predicate); 

PredicateBuilder code is here .

+9
source

if you want to build a predicate based on conditions, use Predicate Builder

+2
source

Source: https://habr.com/ru/post/1489006/


All Articles