gpt4 book ai didi

c# - 为动态关键字构建动态 where 子句或使用 IQueryable C# Linq

转载 作者:太空狗 更新时间:2023-10-29 21:38:57 24 4
gpt4 key购买 nike

我正在尝试使用 LINQ 编写动态 where 子句,以返回包含字符串数组中提供的任何关键字的所有行。到目前为止,结果并没有像我预期的那样返回,查看 SQL 我可以看到问题所在。

IQueryable<comments> query = _db.comments;

if (score != null)
query = query.Where(x => x.score == score);
if (dateFrom != null)3
query = query.Where(x => x.date_created >= dateFrom);
if (dateTo != null)
query = query.Where(x => x.date_created <= dateTo);
if (keywords != null)
{
//how to use OR for each in array?
foreach (var keyword in keywords)
{
var keywordCondition = keyword;
query = query.Where(x => x.text.Contains(keywordCondition));
}

}

WHERE ([Extent1].[score] = @p__linq__0)
AND ([Extent1].[date_created] >= @p__linq__1)
AND ([Extent1].[date_created] <= @p__linq__2)
AND ([Extent1].[text] LIKE @p__linq__3 ESCAPE '~')
AND ([Extent1].[text] LIKE @p__linq__4 ESCAPE '~')

--应该是

WHERE ([Extent1].[score] = @p__linq__0) 
AND ([Extent1].[date_created] >= @p__linq__1)
AND ([Extent1].[date_created] <= @p__linq__2)
AND (([Extent1].[text] LIKE @p__linq__3 ESCAPE '~')
OR ([Extent1].[text] LIKE @p__linq__4 ESCAPE '~'))

我已经花了几个小时寻找解决方案,希望有人能帮助我。

提前致谢

最佳答案

正如您所猜到的,这是您需要更改的有问题的部分,因为它将“AND”所有子句。

//how to use OR for each in array?
foreach (var keyword in keywords)
{
var keywordCondition = keyword;
query = query.Where(x => x.text.Contains(keywordCondition));
}

我认为您可以通过将其更改为:

query = query.Where(x => keywords.Any(kw => x.text.Contains(kw));

关于c# - 为动态关键字构建动态 where 子句或使用 IQueryable C# Linq,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29825773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com