Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to chain alternative conditions in where clause in Entity Framework

I'm trying to rewrite the following query as a 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 resulting query is equal to:

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

Is there any ideas how to do it the right way?

like image 548
dodbrian Avatar asked Jun 30 '13 22:06

dodbrian


2 Answers

The right way... is that. I mean, you could write it as

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

but that's slower, unordered and looks weirder too. I don't know what you're looking for, because the way that you posted is the right way to do it.

However, it seems you want to build the expression dynamically (judging from your comment). If so, then you're looking for a 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);

The code for PredicateBuilder is here.

like image 60
It'sNotALie. Avatar answered Oct 14 '22 09:10

It'sNotALie.


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

like image 45
Guru Stron Avatar answered Oct 14 '22 09:10

Guru Stron