C# ASP.NET Identity:获取角色中的所有用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19490388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:07:35  来源:igfitidea点击:

ASP.NET Identity: get all users in a role

c#asp.netasp.net-mvc-5asp.net-identity

提问by graycrow

How to obtain a list of all users in a role? Before it was possible with Roles.GetUsersInRole, but with new Identity I can't find anything like this.

如何获取角色中所有用户的列表?在 Roles.GetUsersInRole 成为可能之前,但有了新的身份,我找不到这样的东西。

采纳答案by Hao Kung

Its not possible via the RoleManager in 1.0 RTM, in 1.1 it will exposed via an IQueryable RoleManager.Roles. For 1.0, you need to drop down to the implementation layer (i.e. db context)

它不可能通过 1.0 RTM 中的 RoleManager,在 1.1 中它将通过 IQueryable RoleManager.Roles 公开。对于1.0,需要下拉到实现层(即db context)

回答by Vincenzo Costa

You could use the Entity Framework but with Asp.Net Identity 1.0 is not yet possible. You have to wait for the release of Identity 2.0.

您可以使用实体框架,但尚无法使用 Asp.Net Identity 1.0。你必须等待Identity 2.0的发布。

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString)) {
    string queryString = "SELECT AspNetUsers.UserName FROM dbo.AspNetUsers INNER JOIN dbo.AspNetUserRoles ON " + "AspNetUsers.Id=AspNetUserRoles.UserId WHERE AspNetUserRoles.RoleID='" + id + "'";
    SqlCommand command = new SqlCommand(queryString, connection);
    command.Connection.Open();

    List<string> @out = null;
    dynamic reader = command.ExecuteReader();
    while (reader.Read()) {
        if (@out == null) @out = new List<string>();
        @out.Add(reader.GetString(0));
    }

    return @out;
}

回答by ChoptimusPrime

I didn't see a built in way, but it is fairly easy to implement. I have this method in my application specific UserManager:

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

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

The SQL it output seemed reasonable:

它输出的 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)
)

回答by Serj Sagan

This is for the new MVC 5 ASP.NET Identity:

这是新的MVC 5 ASP.NET Identity

var managerRole = TMRoles.GetIdentityRole(TMRoles.Manager);
var managers = managerRole.Users;

public class TMRoles
{
    private static RoleManager<IdentityRole> RoleManager = 
        new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new TMContext()));

    public static string Manager { get { return "Manager"; } }


    public static IdentityRole GetIdentityRole(string roleName)
    {
        return RoleManager.FindByName(roleName);
    }
}

回答by Boris Zinchenko

For some reason, very nice query suggested above by @ChoptimusPrime did not compile for me in ASP.NET Identity 2.2.1. I have written an extended function:

出于某种原因,@ChoptimusPrime 上面建议的非常好的查询在 ASP.NET Identity 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;
}