动态或在EF Core中的使用在哪里?

huangapple go评论71阅读模式
英文:

How dynamic or usage in EF Core Where?

问题

f.XNumber.Contains(item) or 
f.XNumber.Contains(item) or 
f.XNumber.Contains(item) or 
英文:

My sample code block is as follows, I have a string array. This array consists of dynamically not predetermined

var query = _dbContext.Table..;
List<string> arr= ...;
// output: arr=X,Y,Z

foreach (var item in arr)
{
    query = query.Where(f => f.XNumber.Contains(item))
}

The output of the expression I want to do should be like this

f.XNumber.Contains(item) or 
f.XNumber.Contains(item) or 
f.XNumber.Contains(item) or 

but every where causes an and operator. How can I convert it to OR operator? Is there a method like WhereWithOr?

Edit: my data looks like this:

XNumber:
12331X,
5113Y,
5123,
Z5123,
...

I'm trying to find items containing X or Y and Z in field XNumber

答案1

得分: 2

使用 LINQKit  `PredicateBuilder`
```cs
var predicate = PredicateBuilder.New(query);
foreach (var item in arr)
{
    predicate = predicate.Or(f => f.XNumber.Contains(item));
}
query = query.Where(predicate);

或者我的扩展 FilterByItems

query = query.FilterByItems(arr, (f, item) => f.XNumber.Contains(item), true);
英文:

Using LINQKit's PredicateBuilder

var predicate = PredicateBuilder.New(query);
foreach (var item in arr)
{
    predicate = predicate.Or(f => f.XNumber.Contains(item));
}
query = query.Where(predicate);

Or my extension FilterByItems

query = query.FilterByItems(arr, (f, item) => f.XNumber.Contains(item), true);

答案2

得分: 1

你在那里做的是向查询添加多个 Where 子句。Entity Framework 然后将它们组合成一个单独的 Where 子句,显然是由 AND 连接的。

所以你需要使用内部谓词并将其添加到查询的单个 Where 子句中。

这里的一个答案建议使用 PredicateBuilder

英文:

What you're doing there is adding multiple Where clauses to the query. EF then combines them into a single Where claure that, obviously, joined by ANDs.

So youdneed to work with the inner predicate and add that to a single Where in your query.

An answer here suggests using PredicateBuilder

答案3

得分: 0

可以用单个 Where 来实现,类似于这样:

query.Where(f => item.Any(i => f.XNumber.Contains(i)))

这将检查是否可以在数组中至少找到一个项目的匹配项。

英文:

It could be done with a single Where, something like this:

query.Where(f => item.Any(i => f.XNumber.Contains(i)))

This will check if it can find a match for at least 1 item in your array.

huangapple
  • 本文由 发表于 2023年5月17日 16:55:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76270256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定