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
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.
For multiple level of includes, you need ThenInclude
.
var users = _context.Users
.Include(x => x.userProjects)
.ThenInclude(y => y.Project)
.ToListAsync();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.