我正在使用预览版的EF Core 2.1,它应该可以减少N+1查询问题。我试图制作一个查询,选取帖子作者的论坛主题:
dbContext.ForumThreads
.Include(t => t.Posts)
.Take(n)
.Select(t => new
{
t.Id,
t.Title,
PostAuhtors = t.Posts.Select(p => p.Author).Take(5)
}).ToArray();
这会产生n+1个查询:对于每个论坛主题,它选择帖子作者。
这个模式很简单:
public class ForumThread
{
public Guid Id {get;set;}
public string Title {get;set;}
public ICollection<ForumPost> Posts {get;set;}
}
public class ForumPost
{
public Guid Id {get;set;}
public string Author {get;set;}
public string Content {get;set;}
}
Take(5)
会产生n+1个查询,如果不使用Take只会产生2个查询。(#9282) 也许一个替代方案是使用Where子句来限制从主题中发布的帖子?(我知道这不是同一件事...) - Luís Antunes