ASP.NET Core 1.1获得所有用户及其角色 [英] ASP.NET Core 1.1 getting all users and their roles

查看:168
本文介绍了ASP.NET Core 1.1获得所有用户及其角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET的新手,我试图获取所有注册用户及其角色名称的列表,然后使用viewModel将其发送到视图.

I am new to .NET trying to get a list of all the registered user along with their role names and send them to a view using a viewModel.

这是ViewModel:

Here's the ViewModel:

public class ApplicationUserListViewModel
{
    [Display(Name = "User Email Address")]
    public string UserEmail { get; set; }

    public  List<IdentityUserRole<string>> Roles { get; set; }
}

我尝试这样做是为了让所有用户及其角色并为每个用户创建一个ViewModel并将所有视图模型放在列表中以传递给View:

I tried this for getting all users along with their roles and make a ViewModel for each user and put all the view models in a list to pass to the View:

var users =  _userManager.Users.ToList();
var userList = users.Select(u => 
                new ApplicationUserListViewModel {
                    UserEmail = u.Email,
                    Roles = u.Roles.ToList() }
                    ).ToList(); 

但是,当我明确地为每个用户分配了角色时,这总是为每个用户分配0个角色.

But this always gives me 0 roles count for every user when I clearly have roles assigned to every user.

推荐答案

您生气了,但是您的解决方案并不完美,因为它会导致性能问题.您正在对数据库执行一个请求以查询用户,然后在foreach循环中为每个用户执行一个新查询以获取他们的相关角色,这确实很糟糕.如果您的数据库中有X用户,则最终将使用:

You anwsered yourself but your solution is not perfect because it causes performance issue. You're executing one request to your database to query users then in your foreach loop you execute a new query for each user to get their related roles which is really bad. If you've X user in your database you will end up using :

  • 一个查询来获取用户
  • X查询以获取每个用户的角色.

通过在一个查询中包含相关角色,您可以做得更好:

You can do better by including the related roles in one query like this:

foreach (var user in _userManager.Users.Include(u => u.Roles).ToList())
{              
    list.Add(new ApplicationUserListViewModel {
        UserEmail = user.Email,
        Roles = user.Roles
    });
}

或者只是这个:

var users = _userManager.Users.Include(u => u.Roles)
                        .Select(u => new ApplicationUserListViewModel {
                            UserEmail = user.Email,
                            Roles = user.Roles
                        })
                        .ToList();


ASP.NET Core Identity 2.x的更新

此解决方案对于ASP.NET Core Identity 2.x无效,因为IdentityUser不再包含Roles属性.有关ASP.NET Core Identity 2.x,请参见此答案.


Update for ASP.NET Core Identity 2.x

This solution is not valid for ASP.NET Core Identity 2.x as IdentityUser no longer contains a Roles property. See this answer for ASP.NET Core Identity 2.x.

这篇关于ASP.NET Core 1.1获得所有用户及其角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆