与ThenInclude的EF相关数据

时间:2018-03-23 06:00:36

标签: c# ef-core-2.0

在EF Core中返回相关数据的正确且最高效的方法是什么?

我使用连接表UserProjects来表示用户和项目之间的多对多关系。

(用户)1 --- M(UserProject)M --- 1(项目)1 --- M(文件)

如何为当前用户返回特定项目的所有文件?

我目前正在这样做:

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();

型号:

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; }

}

1 个答案:

答案 0 :(得分:-1)

试试这个。

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();