我在多对多关系中有以下数据库表
Article
- Id
ArticleTag
- ArticleId
- TagId
Tag
- Id
*所有ID都是int
我无法弄清楚如何编写LINQ to SQL查询,该查询将返回与属于同一文章的多个标签匹配的文章列表。
实施例: 返回带有标签2和5的文章
Article 1 has tags 2,3,5
Article 2 has tags 2,3,6,7
Article 3 has tags 2,5,9
Article 4 has tags 1,2,9,12
结果只是第1条和第3条
答案 0 :(得分:1)
此查询返回具有标记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