如何使用 LINQ 查询展平 SQL 与集合的连接?

How to flatten an SQL join with collection using LINQ query?

假设我有两个表:Users 和 UserRoles:

Users:
+----+
| Id |
+----+
|  1 |
|  2 |
|  3 |
+----+

UserRoles:
+--------+----------+
| UserId | Name     |
+--------+----------+
|      1 | A        |
|      1 | B        |
|      2 | A        |
|      3 | C        |
+--------+----------+

我需要能够 select 将以上数据转换成如下所示的用户对象列表:

class User
{
   public int Id { get; set; }
   public List<string> Roles { get; set; }
}

我能想到的最好的方法如下,但它最终会生成一个嵌套的 select 语句,我不知道这是否会影响性能:

List<Device> usersWithRoles = from user in Users
   select new Device
   {
      Id = user.Id,
      Roles = (from role in UserRoles where role.UserId == user.Id select role.Name).ToList()
   }.ToList();

有没有更好的(性能更高的方法)来完成这个?例如加入,我在想这样的事情,但不知道如何从加入中填充角色:

List<Device> usersWithRoles = from user in Users
   join user_role in UserRoles on user.Id equals user_role.UserId
   select new Device
   {
      Id = user.Id,
      Roles = ??? // how do I populate this
   }.ToList();

谢谢。

使用 GroupJoin LINQ to SQL 方法:

List<Device> usersWithRoles = from user in Users
   join user_role in UserRoles on user.Id equals user_role.UserId into roles
   select new Device
   {
      Id = user.Id,
      Roles = roles.ToList()
   }.ToList();