【问题标题】:Get nested UserRoles from User table从 User 表中获取嵌套的 UserRoles
【发布时间】:2022-01-07 13:54:41
【问题描述】:

我正在从数据库中查询并且有嵌套表。我的查询如下所示:

  System.Collections.Generic.IEnumerable<ApplicationUser> applicationUsers = await _userManager.Users
        .Include(u => u.UserRoles).ToListAsync();

我想获取所有 UserRole ID 和角色名称,所以我这样做了:

  IEnumerable<List<UserRole>> userRoles = applicationUsers.Select(person => person.UserRoles.Select(u => new UserRole
        {
          Id = u.RoleId,
          RoleName = u.Role.ToString(),
        }).ToList());

但是,当我需要List&lt;UserRole&gt; 时,我得到IEnumerable&lt;List&lt;UserRole&gt;&gt; 的输出。我做错了什么?

UserRole.cs:

  public class UserRole
  {
    public string Id { get; set; }
    public string RoleName { get; set; }
    public bool Successful { get; set; }

  }

【问题讨论】:

  • 尝试用 SelectMany 替换第一个选择。

标签: c# linq


【解决方案1】:

使用

List<UserRole> userRoles = applicationUsers.SelectMany(person => person.UserRoles).ToList();

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2014-08-27
    • 2022-10-12
    • 1970-01-01
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-13
    • 2019-10-27
    相关资源
    最近更新 更多