[英]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? 有没有想法如何以正确的方式做到这一点?
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
: 如果是这样,那么你正在寻找一个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 . PredicateBuilder
的代码就在这里 。
如果你想根据条件构建谓词,请使用Predicate Builder
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.