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完全可能不是理想的,但你必須檢查。 –