如何使用 .net-core 和 Entity Framework Core and Identity 从 thenInclude 获取特定列?

How do i get specific columns from a thenInclude using .net-core and Entity Framework Core and Identity?

一段时间以来我一直在努力使这个查询工作,但我似乎无法实现,问题是我不能 return 只有我想要的那些列

var thread = context.threads.Include(t => t.posts).ThenInclude(p => p.ApplicationUser).Include(t => t.ApplicationUser).Include(t => t.movie).Where(t => t.Id == id)

查询 return 是 ApplicationUser 的所有信息,包括电子邮件和散列密码,当然我不希望我尝试这样做

var thread = context.threads.Include(t => t.posts).ThenInclude(p => p.ApplicationUser).Include(t => t.ApplicationUser).Include(t => t.movie).Where(t => t.Id == id).Select(t => new
            {
                title = t.title,
                body = t.body,
                threadUserName = t.ApplicationUser.UserName,
                postsThread = t.posts
            });

但是当我不得不查询帖子的用户名时我遇到了障碍,所以来自 ThenInclude 的数据,尝试做类似 t.posts.ApplicationUser.UserName 和类似的事情但它没有工作,我如何查询用户名职位? ApplicationUser 是从 Identity net-core 包中的 IdentityUser class 派生的 class。

要查询 postsThread,您可以添加一个新的 Select,例如:

var thread = _appDbContext.Threads
                          .Include(t => t.Posts)
                          .ThenInclude(p => p.ApplicationUser)
                          .Include(t => t.ApplicationUser)
                          .Where(t => t.Id == id)
                          .Select(t => new
                                       {
                                            title = t.Title,
                                            body = t.Body,
                                            threadUserName = t.ApplicationUser.UserName,
                                            postsThread = t.Posts.Select(p => new {
                                                                                      p.Content,
                                                                                      p.ApplicationUser.UserName
                                                                                  })
                                       })
                          .ToList();