我一直试图使这个查询工作一段时间但我似乎无法实现,问题是我不能只返回我想要的那些列
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类的类。
要查询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();