Linq有很多选择

时间:2017-04-14 13:33:36

标签: c# .net asp.net-mvc entity-framework linq

我有两个表有多对多关系,在详细信息页面中我想显示相关帖子,相关帖子是至少有一类当前帖子的帖子。 The Tables 如何选择当前帖子的相关帖子? 我试过这个代码,但这不是我想要的:

    [ChildActionOnly]
    public PartialViewResult GetRelatedPost(int id)
    {
        var relatedposts =
            _db.Posts.Select(x => new { x.Id, x.Title, x.Slug, x.Image, x.IsActive,x.PostType,x.PostCategories })
                .Where(x => x.IsActive && x.Id != id && x.PostCategories.Intersect(_db.PostCategories).Any())
                .OrderByDescending(x => x.Id).Take(20)
                .ToList();
    }

更新 我用这段代码解决了我的问题:

            var posts =
            _db.Posts.Select(x => new { x.Id, x.Title, x.Slug, x.Image, x.IsActive,x.PostType,x.PostCategories })
                .Where(x => x.IsActive && x.Id != id && x.PostCategories.Intersect(_db.PostCategories.Where(y=>y.Posts.Any(p => p.Id==id))).Any())
                .OrderByDescending(x => x.Id).Take(20)
                .ToList();

这是最好的方法吗?

2 个答案:

答案 0 :(得分:0)

我认为您需要在交叉期间选择PostCatagories的主键:

[ChildActionOnly]
public PartialViewResult GetRelatedPost(int id)
{
    var relatedposts =
        _db.Posts.Select(x => new { x.Id, x.Title, x.Slug, x.Image, x.IsActive,x.PostType,x.PostCategories })
            .Where(x => x.IsActive && x.Id != id && x.PostCategories.Select(y => y.Id).Intersect(_db.PostCategories.Select(y => y.Id)).Any())
            .OrderByDescending(x => x.Id).Take(20)
            .ToList();
}).Any())
            .OrderByDescending(x => x.Id).Take(20)
            .ToList();
}

答案 1 :(得分:0)

更新:我用这段代码解决了我的问题:

        var posts =
        _db.Posts.Select(x => new { x.Id, x.Title, x.Slug, x.Image, x.IsActive,x.PostType,x.PostCategories })
            .Where(x => x.IsActive && x.Id != id && x.PostCategories.Intersect(_db.PostCategories.Where(y=>y.Posts.Any(p => p.Id==id))).Any())
            .OrderByDescending(x => x.Id).Take(20)
            .ToList();