fix(perf): eliminate N+1 in UserService.ListAsync with bulk role/site loading

ListAsync called UserManager.GetRolesAsync() per user (N queries
for N users). Now loads all roles and user-site assignments in two
bulk queries, grouped by userId in memory for O(1) lookup.
This commit is contained in:
Arnaud Dartois committed 2026-07-17 19:32:13 +00:00
1 parent b04d8a72c2
commit 0c0437a2cf
1 file changed
+38 -5
@@ -31,11 +31,26 @@ public class UserService : IUserService
.Take(pageSize)
.ToListAsync(ct);
var items = new List<UserResponse>();
foreach (var user in users)
{
items.Add(await MapToResponse(user));
}
var userIds = users.Select(u => u.Id).ToList();
// Bulk-load roles and site assignments (single query each, not N+1)
var roleQuery = from ur in _db.Set<IdentityUserRole<Guid>>()
join r in _db.Roles on ur.RoleId equals r.Id
where userIds.Contains(ur.UserId)
select new { ur.UserId, r.Name };
var rolesByUser = (await roleQuery.ToListAsync(ct))
.GroupBy(x => x.UserId)
.ToDictionary(g => g.Key, g => g.Select(x => x.Name!).ToList());
var sitesByUser = (await _db.UserSites
.Where(us => userIds.Contains(us.UserId))
.ToListAsync(ct))
.GroupBy(us => us.UserId)
.ToDictionary(g => g.Key, g => g.Select(us => us.SiteId).ToList());
var items = users.Select(u => MapToResponse(u,
rolesByUser.GetValueOrDefault(u.Id, []),
sitesByUser.GetValueOrDefault(u.Id, []))).ToList();
return ServiceResult<PagedResult<UserResponse>>.Success(
new PagedResult<UserResponse>(items, total, page, pageSize));
@@ -210,6 +225,24 @@ public class UserService : IUserService
user.CreatedAt);
}
private static UserResponse MapToResponse(AppUser user, List<string> roles, List<Guid> siteIds)
{
return new UserResponse(
user.Id,
user.Email ?? "",
user.DisplayName,
user.Theme,
user.Language,
roles,
siteIds,
user.TwoFactorEnabled,
user.LockoutEnabled && user.LockoutEnd.HasValue && user.LockoutEnd > DateTimeOffset.UtcNow,
user.LockoutEnd?.UtcDateTime,
user.AccessFailedCount,
user.EmailConfirmed,
user.CreatedAt);
}
private static string GenerateTemporaryPassword()
{
const string lower = "abcdefghijklmnopqrstuvwxyz";