您不应该将每个帖子的标签投射到外部查询中;相反,您需要使用内部查询来执行外部过滤器的检查。(在 SQL 中,我们习惯将其称为相关子查询。)
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 的说明进行更正。下面的版本返回的帖子至少包含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;
我曾经在 Transact-SQL.Any() == false
中模拟运算符。NOT EXISTS