LINQ多對多關系,如何寫一個正確的WHERE子句? [英] 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子句?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持IT屋!
查看全文