How to chain alternative conditions in where clause in Entity Framework

.net c# entity-framework linq-to-entities

Question

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?

1
7
6/30/2013 10:25:46 PM

Accepted Answer

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.

11
6/30/2013 11:14:21 PM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow