ASP.NET Identity: get all users in a role

Question!

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.

By : graycrow


Answers

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.

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


This is for the new 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);
    }
}


This video can help you solving your question :)
By: admin