为什么在获取用户列表时获取角色这么慢?

Why is getting roles when getting a list of users so slow?

我正在获取数据库中的所有用户及其相关角色。它有效,但人是它很慢。

        var ctx = new SiteUserContext();
        var ctxUserList = ctx.Users.ToList();


        //var userManager = new UserManager<SiteUser>(new UserStore<SiteUser>(new SiteUserContext()));

        var jsonModels = from user in ctxUserList
                         select new
                         {
                             userName = user.UserName,
                             Roles = (from userRole in user.Roles
                                      join role in ctx.Roles on userRole.RoleId
                                      equals role.Id
                                      select role.Name).ToList(),
                             id = user.Id
                         };

只获取一个用户列表就可以了,100 个用户大约需要 600 毫秒。但是,一旦我尝试添加角色,我就会等待 5-10 秒。每个用户只有 1 或 2 个角色。这并不是一个巨大的查询。

我尝试使用 userManager GetRolesById(user.Id),但速度更慢。 10+ 秒。

如有任何关于快速 运行 的提示,我们将不胜感激。

你这里是执行N+1查询获取用户列表后的信息,然后枚举用户列表进行精简。使用 LINQ 我们可以更有效地做到这一点。我以前用这个在一个过程中做到这一点。

var usersWithRoles = (from user in ctx.Users  
                      select new  
                       {  
                        UserId = user.Id,                                        
                        Username = user.UserName,  
                        Email = user.Email,  
                        RoleNames = (from userRole in user.Roles  
                                     join role in context.Roles on userRole.RoleId   
                                     equals role.Id  
                                     select role.Name).ToList()  
                                  })
                    .ToList()
                    .Select(p => new   
                    {  
                       UserId = p.UserId,  
                       Username = p.Username,  
                       Email = p.Email,  
                       Role = string.Join(",", p.RoleNames)  
                    });  

这应该快得多,只需查询 1 次即可获得!

编辑: 查看您的请求,如果您只想将角色作为列表,则可以跳过此示例中的第二个投影。 (我需要在列表中显示它,因此示例中的 string.Join。