LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)
问题描述
我对我的表使用多对多关系。
存在查询:
var query = from post in context.Posts
from tag in post.Tags where tag.TagId == 10
select post;
好,它工作得很好。我收到由id指定的标签的帖子。
我有一个标签ID集合。我想要获得包含我收藏中每个标签的帖子。
我尝试以下方式:
var tagIds = new int[]{1, 3, 7, 23, 56};
var query = from post in context.Posts
from tag in post.Tags where tagIds.Contains( tag.TagId )
select post;
它不起作用。该查询返回具有任何一个指定标记的所有帖子。
我想获得一个这样的子句,但对于集合中的任何标签计数都是动态的:
post.Tags.Whare(x => x.TagId = 1 && x.TagId = 3 && x.TagId = 7 && ... )
推荐答案
您不应该在外部查询中投影每个帖子的标记;相反,您需要使用执行外部筛选器检查的内部查询。(在SQL中,我们过去称它为correlated subquery。)
var query =
from post in context.Posts
where post.Tags.All(tag => tagIds.Contains(tag.TagId))
select post;
替代语法:
var query =
context.Posts.Where(post =>
post.Tags.All(tag =>
tagIds.Contains(tag.TagId)));
编辑:根据Slauma’s clarification更正。下面的版本返回至少包含tagIds
集合中所有标记的帖子。
var query =
from post in context.Posts
where tagIds.All(requiredId => post.Tags.Any(tag => tag.TagId == requiredId))
select post;
替代语法:
var query =
context.Posts.Where(post =>
tagIds.All(requiredId =>
post.Tags.Any(tag =>
tag.TagId == requiredId)));
编辑2:已根据Slauma更正以上内容。还包括充分利用下面的查询语法的另一个备选方案:
// Project posts from context for which
// no Ids from tagIds are not matched
// by any tags from post
var query =
from post in context.Posts
where
(
// Project Ids from tagIds that are
// not matched by any tags from post
from requiredId in tagIds
where
(
// Project tags from post that match requiredId
from tag in post.Tags
where tag.TagId == requiredId
select tag
).Any() == false
select requiredId
).Any() == false
select post;
我已使用.Any() == false
模拟Transact-SQL中的NOT EXISTS
运算符。
这篇关于LINQ多对多关系,如何写一个正确的WHERE子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:LINQ多对多关系,如何写一个正确的WHERE子句?
基础教程推荐
- C# 9 新特性——record的相关总结 2023-04-03
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
- 从 C# 控制相机设备 2022-01-01