更新时间:2023-02-16 09:48:49
您生气了,但是您的解决方案并不完美,因为它会导致性能问题.您正在对数据库执行一个请求以查询用户,然后在foreach
循环中为每个用户执行一个新查询以获取他们的相关角色,这确实很糟糕.如果您的数据库中有X用户,则最终将使用:
You anwsered yourself but your solution is not perfect because it causes performance issue. You're executing one request to your database to query users then in your foreach
loop you execute a new query for each user to get their related roles which is really bad. If you've X user in your database you will end up using :
通过在一个查询中包含相关角色,您可以做得更好:
You can do better by including the related roles in one query like this:
foreach (var user in _userManager.Users.Include(u => u.Roles).ToList())
{
list.Add(new ApplicationUserListViewModel {
UserEmail = user.Email,
Roles = user.Roles
});
}
或者只是这个:
var users = _userManager.Users.Include(u => u.Roles)
.Select(u => new ApplicationUserListViewModel {
UserEmail = user.Email,
Roles = user.Roles
})
.ToList();
此解决方案对于ASP.NET Core Identity 2.x无效,因为IdentityUser
不再包含Roles
属性.有关ASP.NET Core Identity 2.x,请参见此答案.
This solution is not valid for ASP.NET Core Identity 2.x as IdentityUser
no longer contains a Roles
property. See this answer for ASP.NET Core Identity 2.x.