【问题标题】:Asp.Net .Net 5 Lambda LINQ get the role name associated with the user account in Asp.Net identitiesAsp.Net .Net 5 Lambda LINQ 获取与 Asp.Net 身份中的用户帐户关联的角色名称
【发布时间】:2021-03-06 18:07:44
【问题描述】:

我正在使用带有实体框架 5 的 Asp.Net .Net5

我有 3 张桌子

  1. aspnetuser
  2. aspnetroles
  3. aspnetuserRoles = 链接表

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

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

aspnetuser 表

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

aspnet角色

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

aspnetuserRoles

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

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

【问题讨论】:

    标签: c# asp.net linq asp.net-core .net-5


    【解决方案1】:

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

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

            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; }
        }
    

    然后,输出如下:

    【讨论】:

      猜你喜欢
      • 2021-12-27
      • 2017-07-25
      • 2016-11-27
      • 2017-06-07
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 1970-01-01
      • 2012-05-26
      相关资源
      最近更新 更多