[英]EF related data with ThenInclude
What is the correct and most performant way to return related data in EF Core? 在EF Core中返回相关数据的正确,最高效的方法是什么?
I'm using a join table UserProjects to represent a many-to-many relationship between users and projects. 我正在使用联接表UserProjects来表示用户和项目之间的多对多关系。
(User)1---M(UserProject)M---1(Project)1---M(File) (用户)1 --- M(UserProject)M --- 1(项目)1 --- M(文件)
How would I return all files on a specific project for the current user? 如何为当前用户返回特定项目上的所有文件?
I'm currently doing it like this: 我目前正在这样做:
var userId = new Guid(_userManager.GetUserId(User));
var files = _dbContext.Users
.Include(up => up.UserProjects)
.ThenInclude(p => p.Project)
.ThenInclude(f => f.Files)
.Where(u => u.Id == userId)
.Single()
.UserProjects.Select(up => up.Project)
.Where(p => p.Id == projectId)
.Single().Files.ToList();
Models: 楷模:
public class ApplicationUser : IdentityUser<Guid>
{
public virtual ICollection<UserProject> UserProjects { get; set; }
}
public class UserProject
{
public Guid ApplicationUserId { get; set; }
public ApplicationUser User { get; set; }
public Guid ProjectId { get; set; }
public Project Project { get; set; }
}
public class Project
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<UserProject> UserProjects { get; set; }
public virtual ICollection<File> Files { get; set; }
}
public class File
{
public Guid Id { get; set; }
public string Name { get; set; }
[Required]
public Project Project { get; set; }
}
Try this one. 试试这个。
var userId = new Guid(_userManager.GetUserId(User));
var files = _dbContext.Files
.Include(p => p.Project)
.ThenInclude(up => up.UserProjects)
.ThenInclude(u => u.User)
.Where(x => x.Project.UserProjects.User.Id == userId)
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.