Asp.Net .Net 5 Lambda LINQ 获取与 Asp.Net 身份中的用户帐户关联的角色名称

Asp.Net .Net 5 Lambda LINQ get the role name associated with the user account in Asp.Net identities

我正在使用 Asp.Net .Net5 和 Entity framework 5

我有 3 table

  1. aspnetuser
  2. aspnetroles
  3. aspnetuserRoles = link table

我当前的 LINQ 代码 return 返回来自用户和用户角色的所有数据,但 none 来自 aspnetrole table。我希望它 return 支持用户和他们当前分配的角色,以便我可以查看他们是管理员还是标准。

    public async Task<IList<User>> GetAllEnabledAccounts()
    {
        var users = await _context.Users
            .Where(u => u.IsEnabled == true)
            .Include(r => r.UserRoles)
            .ToListAsync();
                    
        return users;
    }      

aspnetuser table

id | username
--------------
1  | Jim
2  | Harry

aspnetRoles

id | name
----------
1  | admin
2  | standard

aspnetuserRoles

userId | roleId
----------------
   1   |   1
   2   |   2

查询时应该return 返回用户 Jim,显示他是管理员,Harry 显示他是标准帐户。如何输入 LINQ 查询以正确输出信息?

根据您的代码,我想配置了 aspnetuser 和 aspnetRoles many-to-many relationship,对吗?如果是这样,您可以参考下面的示例,并使用 InCludeThenInCludeSelectMany 方法查询相关实体。

示例代码如下(The Authors 和 Books table 包含多对多关系,BookAuthor 是 join table,类似于 aspnetuserRoles table):

        var result = _dbcontext.Authors
            .Include(c => c.BookAuthor)
            .ThenInclude(c => c.Book)
            .SelectMany(c => c.BookAuthor.Select(d => new BookAuthorViewModel()
            {
                Id = d.Author.Id,
                AuthorName = d.Author.AuthorName,
                BookName = d.Book.BookName,
                ISBN = d.Book.ISBN
            })).ToList(); 

以下机型:

    public class Book
    {
        [Key]
        public int Id { get; set; }

        public string BookName { get; set; }
        public string ISBN { get; set; }

        public IList<BookAuthor> BookAuthor { get; set; }

    }

    public class Author
    {
        [Key]
        public int Id { get; set; }
        public string AuthorName { get; set; }

        public IList<BookAuthor> BookAuthor { get; set; }

    } 

    public class BookAuthor
    {
        public int BookId { get; set; }
        public Book Book { get; set; }

        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

创建一个 ViewModel 来显示查询结果。

    public class BookAuthorViewModel
    {
        [Key]
        public int Id { get; set; }
        public string BookName { get; set; }
        public string AuthorName { get; set; }
        public string ISBN { get; set; }
    }

然后,输出如下: