0
我有两个表与多对多的关系,在一个后细节页面我想显示相关帖子,相关帖子是至少有一个当前帖子类别的帖子。 如何选择当前帖子的相关帖子? 我试着用这个代码,但它不是我想要的:Linq多对多选择
[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();
}
UPDATE: 我解决我的问题与此代码:
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();
是它的最好方法是什么?
也许是作为后容易.Categories.SelectMany(主题);选择你的主文章,并包括.Categories.Posts,如果你想加载它们。 –
@AlexPaven我该怎么做?请帮助我更多 – Mike
好吧保持投影我在想什么像.Where(x => x.Categories.Any(c => c.Posts.Any(p => p.Id == id)))。生成的SQL完全可能不是理想的,但你必须检查。 –