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子句?


基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01