title: EF Core: many-to-many query
body: <p>I am trying to return all items in UserDTO from a User given a particular Team. The below code only returns the UserId (since that is what contained in TeamUser). Can this be done in a straightforward way? Or do I have to perform a second lookup on Users once the UserId's are given?</p>
  <pre><code>public class User
  {
      public long UserId { get; set; }         
      public string? Name { get; set; }
      [Required]
      [EmailAddress]
      public string? Email { get; set; } = default!;
      [Required]
      public string? CreatedDate { get; set; }
      /* relationships */
      public virtual ICollection&lt;TeamUser&gt;? Teams { get; set; } //many Teams to many Users
  }
  
  public class Team 
  {
      public long TeamId { get; set; }  
      [Required]       
      public string? Name { get; set; }        
      [Required]
      public string? CreatedDate { get; set; }
      /* relationships to User */       
      public virtual ICollection&lt;TeamUser&gt;? Users { get; set; } //many Users to many Teams
  }  
  
  public class UserDTO
  {
      public long UserId { get; set; }
      public string? Name { get; set; }
      [Required]
      [EmailAddress]
      public string? Email { get; set; } = default!;
  }
  
  public class TeamUser
  {
      public long TeamId { get; set; }
      public Team? Team { get; set; }
      public long UserId { get; set; }
      public User? User { get; set; }
  }    
  
  [HttpGet]
      public async Task&lt;ActionResult&lt;IEnumerable&lt;UserDTO&gt;&gt;&gt; GetUsers(long? userId, long? teamId)
      {
          if(teamId == null)
          {
              return await _context.Users.Select(x =&gt; UserToDTO(x)).ToListAsync();
          }
          else
          {
              // get users given teamId
              return await _context.TeamUsers
                                      .Include(u =&gt; u.User)
                                      .Where(t =&gt; t.TeamId == teamId)
                                      .Select(pt =&gt; new UserDTO
                                      {
                                          UserId = pt.UserId
                                      })
                                      .ToListAsync();                
          }    
  </code></pre>