How to get IdentityUser roles' names in View?

1.6k views Asked by At

Using ASP.NET MVC5 user identity, I am trying to display IdentityUser's role names in view.

It seems like Identity user has Roles property, which represent collection of IdentityUserRole, instead of IdentityRole. The difference is IdentityUserRole represents association between IdentityUser and IdentityRole, while IdentityRole is the actual Role model [+]. Apparently there is no navigation defined between IdentityUser and IdentityRole. So all we get is RoleId from IdentityUserRole.

  1. Is there an easy way to get the roles names?
  2. Using Fluent API, can we define a virtual navigation property between IdentityRole and IdentityUserRole to get name easily throughout the project?
  3. If it is by design, what is the benefit of not letting us obtain IdentityRole straightforwardly?
1

There are 1 answers

0
MFasseur On

You can select a userrole in identity using the rolemanager

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(this.dbcontext));

from the user get the userrole and then select the name from that role

roleManager.FindById(user.RoleId).Name