Question

I have an MVC 5 application that is using Entity Framework and the repository pattern. I have a repository for the user table (AspNetUsers) and a method within the repository called GetAll() that gets all of the users from that table.

I need to display all of the users and their roles to the user of my application, but I am having difficulty getting to the actual names of the roles through my user repository. The GetAll() method I've written correctly gives me back all of the users along with their role id's, as defined in the association table AspNetUserRoles, but I need to also load the role names.

The line of code that gets me all of the users from my repository looks something like this:

var users = UsersRepository.GetAll();

What I want is to also get the role names for the roles assigned to the users so I can display in the application.

For those unfamiliar with the ASP.NET Identity tables, there is one table that has user information that looks something like this (only relevant fields listed for brevity):

AspNetUsers

  • Id
  • UserName

Then there is another table that has role information that looks something like this (only relevant fields listed for brevity):

AspNetRoles

  • Id
  • Name

Finally, there is an association table in the middle that looks something like this:

AspNetUserRoles

  • UserId
  • RoleId

So my basic goal is to travel from the user objects through the association table to get the role names all within my repository query. I was thinking something like:

var usersAndRoles = UsersRepository.GetAll().Include(.......)
Was it helpful?

Solution

Why are you doing this? You can easily retrieve the users and their roles by using built in identity functionality.

var user = UserManager.FindByName(User.Identity.Name);
var roles = UserManager.GetRoles(user.Id);

GetRoles returns a list of Role Names as strings.

You could also just do this:

var user = UserManager.FindByName(User.Identity.Name);
var roles = user.Roles.Select(x => x.Role.Name).ToList()

If you don't want to get each user individually, then you can simply do this:

using (var db = new ApplicationDbContext()) {
    var query = from q in db.Users 
        select new {User = q.UserName, Roles = q.Roles.Select(x => x.Role.Name)};
}

OTHER TIPS

To get a list of all Roles it is recommended to use roleManager.Roles.

But you can also use the DB context:

IdentityDbContext db = new IdentityDbContext(); // Where IdentityDbContext = your database context.

db.Roles.ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top