How to use an ICollection navigation property with include()

c# entity-framework-core linq

Question

I am trying to get each user with its projects using entity framework core in a web api project in the controller with linq

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

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

1
-2
6/15/2019 7:29:50 PM

Accepted Answer

For multiple level of includes, you need ThenInclude.

var users = _context.Users
                    .Include(x => x.userProjects)
                        .ThenInclude(y => y.Project)
                    .ToListAsync();
0
6/15/2019 7:52:10 PM

Popular Answer

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.

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.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow