如何使用 LINQ 进行简单的 OR 查询?
我正在使用 LINQ to Entities,并且尝试执行简单的 OR 查询。我有一个名为“链接”的表,当我运行查询时,我想包含包含标签列表中任何标签的所有链接以及与搜索词匹配的所有链接。例如:
var tags = new List<string>
{
"games",
"events",
"recipes"
};
var searchTerms = new List<string>
{
"hockey",
"barbecue",
"cheesecake",
"basketball"
}
var links = _entityContainer.Links
.Where(x => x.Tags.Any(y => tags.Contains(y.Name))
.Where(x => searchTerms.Any(y => x.Title.Contains(y)));
注意:链接实体有一个名为 Tags
的导航属性,因此在第一个 .Where()
中,我检查链接集合中的每个标签以查看如果我正在搜索的标签列表包含其中之一。
在第二个 .Where()
中,我只是检查链接的 Title 属性是否包含任何搜索词。
我的问题是,此代码包含所有链接,这些链接至少包含列表中的一个标签并与其中一个搜索词匹配。但我想把两者放在一起。我希望我的链接列表包含与列表中的 1 个或多个标签匹配或与列表中的 1 个或多个搜索词匹配的所有链接。
由于 tags.Contains()
和 searchTerms.Any()
我也遇到了问题,因为这些调用无法转换为要传递给 EF 的表达式。如果我执行ToList()
,它们就会起作用,但我不能这样做,因为它会将大量记录拉入内存。
对于实现我的目标有什么建议吗?
I am using LINQ to Entities and I'm trying to do a simple OR query. I have a table called "Links" and when I run a query I want to include all links containing any tag from a list of tags and all links matching a search term. For example:
var tags = new List<string>
{
"games",
"events",
"recipes"
};
var searchTerms = new List<string>
{
"hockey",
"barbecue",
"cheesecake",
"basketball"
}
var links = _entityContainer.Links
.Where(x => x.Tags.Any(y => tags.Contains(y.Name))
.Where(x => searchTerms.Any(y => x.Title.Contains(y)));
Note: a link entity has a navigation property called Tags
so in the first .Where()
I'm checking each of the tags in the link's collection to see if the list of tags I'm searching for contains one of them.
In the second .Where()
I'm simply checking if the link's Title property contains any of the search terms.
My problem is that this code includes all links that contain at least one tag from the list AND match one of the search terms. But I want to include both together. I want my links list to include all links that either match 1 or more tags in the list OR match 1 or more search terms in the list.
I also have an issue because of tags.Contains()
and searchTerms.Any()
because these are calls that cannot be converted into expressions to be passed to EF. They would work if I did ToList()
but I cannot do that as it would pull a very large number of records into memory.
Any suggestions for accomplishing my goal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将其压缩为一个Where 子句:
Condense it to one Where clause: