6

I am trying to get an IList<ApplicationRole> of roles in which a user is currently enrolled.

Now in the Usermanager class I see there is a function call IList<String> usersRoles = userManager.GetRoles(id); But it just returns the name of the Role as a string. This doesn't help me as I need the id , name and the description of the role.

How can I make a similar call but receive an applicationRole back and not a string?

here is my model:

   public class ApplicationRole : IdentityRole
{
    [Display(Name = "Description")]
    [StringLength(100, MinimumLength = 5)]
    public string Description { get; set; }

}
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
Zapnologica
  • 22,170
  • 44
  • 158
  • 253

3 Answers3

10

I think you need to query the ApplicationDbContext for it as there's no obvious way to get it with a single call from the UserManager or UserStore APIs...

var context = new ApplicationDbContext();
var roles = await context.Users
                    .Where(u => u.Id == userId)
                    .SelectMany(u => u.Roles)
                    .Join(context.Roles, ur => ur.RoleId, r => r.Id, (ur, r) => r)
                    .ToListAsync();
Anthony Chu
  • 37,170
  • 10
  • 81
  • 71
10

I think you're looking for RoleManager. It's very similar in form and function to UserManager, but is specifically intended for CRUD with roles.

var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

Where context is an instance of your DbContext.

Then, you can do:

var role = await RoleManager.FindByIdAsync(roleId);

Or

var role = await RoleManager.FindByNameAsync(roleName); 
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
0

You can try this to get a list of ApplicationRoles.

 List<string> roleNames = UserManager.GetRoles(userId).ToList();

 List<ApplicationRole> roles = RoleManager.Roles.Where(r => roleNames.Contains(r.Name)).ToList();
Andrew Sin
  • 63
  • 5