如何在EF Core中调用ThenInclude两次?

tin*_*ker 13 c# entity-framework entity-framework-core

我正在创建一个ASP.NET Core API应用程序,并依赖于EF Core.我有像这样定义的实体:

public class AppUser : IdentityUser
{
    public string FirstName { get; set; }

    public string LastName { get; set; }

    [InverseProperty(nameof(Post.Author))]
    public ICollection<Post> Posts { get; set; } = new List<Post>();
}

public class Post
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string AuthorId { get; set; }

    [ForeignKey("AuthorId")]
    public virtual AppUser Author { get; set; }

    [InverseProperty(nameof(Like.Post))]
    public ICollection<Like> Likes { get; set; } = new List<Like>();

    [InverseProperty(nameof(Comment.Post))]
    public ICollection<Comment> Comments { get; set; } = new List<Comment>();
}
Run Code Online (Sandbox Code Playgroud)

CommentLike一些其他的实体.请注意,为简洁起见,我简化了实体.然后,我想获得Posts一个用户的,而且还包括LikesComments该帖子已经得到.所以,我做了这样的事情:

return _context.Users
               .Include(u => u.Location)
               .Include(u => u.Posts)
                    .ThenInclude(p => p.Comments)
                        .ThenInclude(c => c.Owner)
               .Include(u => u.Posts)
                    .ThenInclude(p => p.Likes)
                        .ThenInclude(l => l.Giver)
               .Where(u => u.Id == userId)
               .FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)

现在,这很好用,但你可以看到我打了.Include(u = u.Posts)两次电话.有没有办法ThenInclude在同一个属性上调用两次,而没有实际写Include两次语句?

Jan*_* Go 39

现在,这种方法很好,但是你可以看到我正在调用.Include(u = u.Posts)两次.有没有办法在同一属性上调用ThenInclude两次,而实际上也没有两次写Include语句?

调用Include(u => u.Posts)两次是正确的方法.

来自EF Core docs ...强调最后一句话.

您可能希望为其中一个实体包含多个相关实体.例如,查询时BlogS,你有Posts,然后想以包括AuthorTagsPosts.为此,您需要指定从根开始的每个包含路径.例如,Blog -> Posts -> AuthorBlog -> Posts -> Tags.这并不意味着您将获得冗余连接,在大多数情况下,EF将在生成SQL时合并连接.

using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Author)
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Tags)
        .ToList();
}
Run Code Online (Sandbox Code Playgroud)

  • Microsoft实施“ AlsoInclude()”的好时机,以防止您不得不多次编写相同的include语句 (13认同)
  • 我输入 AlsoInclude 却不知道不存在这样的!! (8认同)

viv*_*una 8

您不能使用ThenInclude多个导航属性。你必须有Include

这是为此打开的错误

  • 我注意到在 Include 中指定完整路径也有效,例如 Include(u =&gt; u.Posts) .Include(u =&gt; u.Posts.Comments) 这是否等效?有什么缺点吗? (2认同)