【发布时间】:2017-04-14 13:33:36
【问题描述】:
我有两个具有多对多关系的表,在帖子详细信息页面中我想显示相关帖子,相关帖子是至少具有当前帖子类别的帖子。 如何选择当前帖子的相关帖子? 我尝试使用此代码,但这不是我想要的:
[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();
这是最好的方法吗?
【问题讨论】:
-
也许就像 post.Categories.SelectMany(Posts);选择您的主要帖子并包含 .Categories.Posts 如果您想立即加载它们。
-
@AlexPaven 我该怎么做?请帮助我更多
-
好的,保持投影我在想像 .Where(x => x.Categories.Any(c => c.Posts.Any(p => p.Id == id))) .不过,生成的 SQL 完全有可能并不理想,您必须检查一下。
标签: c# .net asp.net-mvc entity-framework linq