I'm trying to get a list of devices that have been registered to users based on a specific project.
My schema is as follows:
I have a many to many relationship between my Users and Projects table and that is done by a join table called ProjectUsers. My devices table is joined to users by a UserId field.
I need my list of devices to be returned based on the project ID but I'm having a hard time using Join<>
because my ProjectUsers entity doesn't exist in my context.
Ultimately this is the query I need and when I run this in SSMS, I get the results I want:
select d.* from devices d
join users u on u.id = d.userid
join projectusers pu on pu.userid = u.id
join projects p on p.id = pu.projectid
where p.id = 7
Here are my models if this helps: Users:
public class User : IInt32Identity
{
public int Id { get; set; }
public string UserEmail { get; set; }
public List<ProjectUsers> ProjectUsers { get; set; }
...
}
Projects:
public class Project : IInt32Identity
{
public int Id { get; set; }
public string ProjectName { get; set; }
public List<ProjectUsers> ProjectUsers { get; set; }
...
}
ProjectUsers:
public class ProjectUsers
{
public int UserId { get; set; }
public User User { get; set; }
public int ProjectId { get; set; }
public Project Project { get; set; }
}
Devices:
public class Device : IInt32Identity
{
public int Id { get; set; }
public string Name { get; set; }
public int UserId { get; set; }
...
}
EDIT: Adding code that is working as two different expressions. When I combine them into a single expression (replace my "temporary" users object in the second expression with the full first expression), it does not work.
List<User> users = _context.Users
.Include(x => x.ProjectUsers)
.ThenInclude(b => b.Project)
.Where(x => x.ProjectUsers
.Any(y => y.ProjectId == id))
.ToList();
List<Device> devices = _context.Devices
.Where(x => users
.Any(l => x.UserId == l.Id))
.ToList();
return devices;