ASP.NET Core 1.1 getting all users and their roles

耗尽温柔 提交于 2019-12-07 00:07:29

问题


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.

Here's the ViewModel:

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

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

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(); 

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


回答1:


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 :

  • One query to get users
  • X queries to get each user's roles.

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

Or just this:

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

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.




回答2:


Well, I got this working. This is probably not how it should be done but it works fine.

var list = new List<ApplicationUserListViewModel>();

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


来源:https://stackoverflow.com/questions/43562150/asp-net-core-1-1-getting-all-users-and-their-roles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!