How to get the identifier of roles for which the user is registered in MVC 5

I am trying to get the IList<ApplicationRole>roles in which the user is currently registered.

Now in the Usermanager class I see that there is a function call IList<String> usersRoles = userManager.GetRoles(id);But it just returns the role name as a string. It does not help me, because I need it id, nameand descriptionfor this role.

How can I make a similar call, but get the Role application back, not a string?

here is my model:

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

}
+4
source share
3 answers

, ApplicationDbContext , API UserManager UserStore...

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();
+8

, RoleManager. UserManager, CRUD .

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

context - DbContext.

:

var role = await RoleManager.FindByIdAsync(roleId);

var role = await RoleManager.FindByNameAsync(roleName); 
+9

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();
0
source

All Articles