此查询返回恰好具有标签 2 和 5 的文章 ID:
ctx.ArticleTags.Where(at => at.TagId == 2 || at.TagId == 5)
.GroupBy(at => at.ArticleId)
.Where(group => group.Count() == 2)
.Select(group => group.Key);
生成的 SQL 将是:
SELECT ArticleId
FROM ArticleTag
WHERE TagId = 2 OR TagId = 5
GROUP BY ArticleId
HAVING Count(1) = 2
对于通用的,如果我们假设您有一个标签列表,您可以扩展comportement:
var tagIds = new List<int>(){ 2, 5 };
ctx.ArticleTags.Where(at => tagIds.Contains(at.TagId))
.GroupBy(at => at.ArticleId)
.Where(group => group.Count() == tagIds.Count)
.Select(group => group.Key);
请注意,在这种情况下,生成的 SQL 将使用IN
而不是列表或OR
:
SELECT ArticleId
FROM ArticleTag
WHERE TagId in (2, 5)
GROUP BY ArticleId
HAVING Count(1) = 2