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

问题描述 投票:0回答:1

我一直试图使这个查询工作一段时间但我似乎无法实现,问题是我不能只返回我想要的那些列

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)

查询返回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
            });

但是,当我必须查询帖子的UserName以便来自ThenInclude的数据,尝试做类似t.posts.ApplicationUser.UserName和类似的东西但它没有工作时,我遇到了障碍,我如何查询帖子的用户名? ApplicationUser是一个派生自Identity net-core包中的IdentityUser类的类。

c# asp.net entity-framework asp.net-core asp.net-identity
1个回答
0
投票

要查询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();
© www.soinside.com 2019 - 2024. All rights reserved.