Users and Roles, can this be made more efficient?

Hi I’m new MVC Core 2.2. I’m trying to create an administrative Users page which List the Users and their Role(They will only be assigned a single role). In my TestController I have an action with the following code, which actually works. But is it an acceptable way of getting Users and their roles? It would seem like a database join maybe a little faster but I do not know how to achieve that. Here is the action code, how can I do this better?

   public async Task<IActionResult> UserListTest()
        var users = _userManager.Users;
        foreach(ApplicationUser user in users)
            var roles = await _userManager.GetRolesAsync(user);
            user.RoleName = roles.DefaultIfEmpty("none").First();
        return View(users);

I would think that you can get all users including all their roles by using:
var users = _userManager.Users.Include(u => u.Roles);
This tells the database to not only retrieve each user record but also the associated roles for each user.
But as you’re using .NET Core, it probably won’t work! They have been complaining about this at

1 Like

Thank You for replying to my question. I’m beginning to think you are correct. I will certainly give your suggestion a try but, by the amount of replies here and so many googles attempts without a clean solution, I believe I will just have to “Long Hand” it. I hope your suggestion works though.


.NET Foundation Website | Blog | Projects | Code of Conduct