且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ASP.NET Core 1.1获得所有用户及其角色

更新时间:2023-02-16 09:48:49

您生气了,但是您的解决方案并不完美,因为它会导致性能问题.您正在对数据库执行一个请求以查询用户,然后在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.