We have a method to load all ASP.NET Core Identity users
await _userManager.Users.ToListAsync()
And we also have a method to load roles of a particular identity user:
IList<string> userRoles = await UserManager.GetRolesAsync(userId);
But is there any way to load all identity users with their roles in one call? Basically one database call.
Because if I want to load all the users and want to return their roles also in a dto I will have to loop through all the users and then have to hit the database for all the users to get their role is quite inefficient
Is there any way we can load both these information together for all the users in one call?
To achieve your requirement you could try EF to create quires. below is sample code which will help you load all users and their role information at once.
using Microsoft.EntityFrameworkCore;
var usersWithRoles = await _context. Users
. Include(u=> u.UserRoles)
. ThenInclude(ur => ur. Role)
. Select(u => new
{
User = u,
Roles = u.UserRoles.Select(ur => ur.Role.Name). ToList()
})
. ToListAsync();