Getting a list of users with their assigned role in Identity 2

前端 未结 2 1716
旧巷少年郎
旧巷少年郎 2021-02-14 21:56

I am stuck trying to get this output

Id | Name   | Role
----------------------------
1  | John   | Administrator
----------------------------
2  | Mary   | Manag         


        
相关标签:
2条回答
  • 2021-02-14 22:33

    If you are using ASP.NET Identity 2, you have to add some codes to AccountContoller. Add an ActionResult to get UserList. You also nedd ApplicationDbContext instance and get it from OwinContext :

    public class AccountController : Controller
    {
        private ApplicationUserManager _userManager;
        private ApplicationSignInManager _signInManager;
    
        public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
        {
            UserManager = userManager;
            SignInManager = signInManager;
        }
    
        public ActionResult UserList()
        {
            var applicationDbContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
            var users = from u in applicationDbContext.Users
                        from ur in u.Roles
                        join r in ApplicationDbContext.Roles on ur.RoleId equals r.Id
                        select new
                        {
                            u.Id,
                            Name = u.UserName,
                            Role = r.Name,
                        };
    
                // users is anonymous type, map it to a Model 
                return View(users);
        }
        .
        .
        .
    }
    

    Update - if user has multiple roles:

    from user in applicationDbContext.Users
    select new
    {
        user.Id,
        user.UserName,
        Roles = applicationDbContext.Roles.Where(r => user.Roles.Select(ur => ur.RoleId).Contains(r.Id)).Select(r => r.Name)
    }
    
    0 讨论(0)
  • 2021-02-14 22:55

    This will help you

        using(ApplicationDbContext db=new ApplicationDbContext())
        {
              var users = (from user in db.Users
                           from roles in user.Roles
                           join role in db.Roles
                           on roles.RoleId equals role.Id 
                           select new
                           {
                               user.UserName, 
                               role.Name
                           }).ToList(); 
        }
    
    0 讨论(0)
提交回复
热议问题