LINQ多对多关系,如何写一个正确的WHERE子句? [英] LINQ many-to-many relationship, how to write a correct WHERE clause?

查看:0
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆