简体   繁体   English

如何在 include() 中使用 ICollection 导航属性

[英]How to use an ICollection navigation property with include()

I am trying to get each user with its projects using entity framework core in a web api project in the controller with linq我正在尝试使用 linq 在控制器中的 web api 项目中使用实体框架核心来获取每个用户的项目

I tried with this query but it gave me an empty object我试过这个查询,但它给了我一个空对象

var users = _context.Users.Include(x => x.userProjects.Select(up => up.UserId == x.Id)).ToListAsync();

I also tried this one and got the same result我也尝试了这个并得到了相同的结果

var users = _context.Users.Include(x => x.userProjects.Where(up => up.UserId == x.Id)).ToListAsync();

This is the User class这是用户类

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }


    public ICollection<UserProject> userProjects { get; set; }
}

This is the Project class这是项目类

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<User> Users { get; set; }
    public ICollection<UserProject> UserProjects { get; set; }
}

and this is the UserProject class这是 UserProject 类

public class UserProject
{
    [ForeignKey("User")]
    public int UserId { get; set; }
    public User User { get; set; }

    [ForeignKey("Project")]
    public int ProjectId { get; set; }
    public Project Project { get; set; }
}

I want to get a json with each user and an array of its projects我想获取每个用户的 json 及其项目数组

var users = _context.Users.Include(u => u.userProjects)
                          .ThenInclude(up => up.Projects))
                          .Where(u => u.UserId == Id)
                          .ToListAsync();

What happens here:这里发生了什么:

You will retrieve all users which have UserId = yourId and also all the UserProjects and Projects of those users.您将检索具有UserId = yourId所有用户以及这些用户的所有UserProjectsProjects

Example of code which shows you you can access all the projects of the first returned user:显示您可以访问第一个返回用户的所有项目的代码示例:

var projectsForFirstUser = users.First().Select(x => x.UserProjects).Select(x => x.Project).ToList();

EDIT: Modified to ThenInclude because of EF Core.编辑:修改为ThenInclude因为 EF Core。

For multiple level of includes, you need ThenInclude .对于多级包含,您需要ThenInclude

var users = _context.Users
                    .Include(x => x.userProjects)
                        .ThenInclude(y => y.Project)
                    .ToListAsync();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM