asp.netasp.net-mvcasp.net-mvc-5asp.net-identityuser-roles

How to get the IDs of IdentityRoles for which a user is enrolled in MVC 5


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 called GetRolesAsync(), but it just returns a list of role names IList<String>. This doesn't help me as I need not only the Name property, but also the Id and Description properties of the roles.

How can I make a similar call but receive an IList<ApplicationRole> list of roles back and not an IList<String> of role names?

ApplicationRole

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

Solution

  • 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();