ASP.NET标识:让角色中的所有用户都可以

gra*_*row 9 c# asp.net asp.net-mvc-5 asp.net-identity

如何获取角色中所有用户的列表?在使用Roles.GetUsersInRole之前,但是使用新的Identity我找不到这样的东西.

Cho*_*ime 11

我没有看到内置方式,但它实现起来相当容易.我在我的应用程序特定的UserManager中有这个方法:

public IQueryable<User> GetUsersInRole(string roleName)
{
    return from user in Users
           where user.Roles.Any(r => r.Role.Name == roleName)
           select user;
}
Run Code Online (Sandbox Code Playgroud)

它输出的SQL似乎合理:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[Email] AS [Email], 
[Extent1].[EmailConfirmed] AS [EmailConfirmed], 
[Extent1].[PasswordHash] AS [PasswordHash], 
[Extent1].[SecurityStamp] AS [SecurityStamp], 
[Extent1].[PhoneNumber] AS [PhoneNumber], 
[Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed], 
[Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled], 
[Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc], 
[Extent1].[LockoutEnabled] AS [LockoutEnabled], 
[Extent1].[AccessFailedCount] AS [AccessFailedCount], 
[Extent1].[UserName] AS [UserName]
FROM [dbo].[AspNetUsers] AS [Extent1]
WHERE  EXISTS (SELECT 
    1 AS [C1]
    FROM  [dbo].[AspNetUserRoles] AS [Extent2]
    INNER JOIN [dbo].[AspNetRoles] AS [Extent3] ON [Extent2].[RoleId] = [Extent3].[Id]
    WHERE ([Extent1].[Id] = [Extent2].[UserId]) AND ([Extent3].[Name] = @p__linq__0)
)
Run Code Online (Sandbox Code Playgroud)


Bor*_*nko 9

出于某种原因,上面提到的@ChoptimusPrime的非常好的查询在ASP.NET身份2.2.1中没有为我编译.我写了一个扩展函数:

public static IQueryable<User> GetUsersInRole(DbContext db, string roleName)
{
  if (db != null && roleName != null)
  {
    var roles = db.Roles.Where(r => r.Name == roleName);
    if (roles.Any())
    {
      var roleId = roles.First().Id;
      return from user in db.Users
             where user.Roles.Any(r => r.RoleId == roleId)
             select user;
    }
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)


小智 6

例如,如果您想要具有“User”角色的用户列表

var users = await (from user in _dbContext.Users
                                 join userRole in _dbContext.UserRoles
                                 on user.Id equals userRole.UserId
                                 join role in _dbContext.Roles 
                                 on userRole.RoleId equals role.Id
                                 where role.Name == "User" 
                                 select user)
                                 .ToListAsync();
Run Code Online (Sandbox Code Playgroud)


Hao*_*ung 5

它不可能通过1.0 RTM中的RoleManager,在1.1中它将通过IQueryable RoleManager.Roles公开.对于1.0,您需要下拉到实现层(即数据库上下文)