How to list users with role names in ASP.NET MVC 5

后端 未结 5 1127
栀梦
栀梦 2021-02-02 18:10

I have default project template of ASP.NET MVC 5 web site and I am trying to list all users with role names (not IDs).

The query is:

db.Users.Include(u =         


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-02 18:33

    The way I do it is:

    using (var userManager = new UserManager(new UserStore(new ApplicationContext()))
    {
        var rolesForUser = await userManager.GetRolesAsync(userId);
    
       // rolesForUser now has a list role classes.
    }
    

    The identity team made two managers: RoleManager for sorting out roles (not user roles though) and UserManager basically for everything authentication wise. There is also a SignInManager as well but not needed.

    So UserManager finds users, creates users, deletes users, sends emails .... the list goes on.

    So my Action could look like this:

        public async Task GetRolesForUser(string userId)
        {
            using (
                var userManager =
                    new UserManager(new UserStore(new ApplicationDbContext())))
            {
                var rolesForUser = await userManager.GetRolesAsync(userId);
    
                return this.View(rolesForUser);
            }
        }
    

    To execute raw SQL then you can do something like this:

    Create the class that Entity Framework can map to, based on the output of your query:

    public class UserWithRole
    {
        public string UserName {get;set;} // You can alias the SQL output to give these better names
        public string Name {get;set;}
    }
    
    using (var context = new DbContext())
    {
        var sql = @"
                    SELECT AspNetUsers.UserName, AspNetRoles.Name 
                    FROM AspNetUsers 
                    LEFT JOIN AspNetUserRoles ON  AspNetUserRoles.UserId = AspNetUsers.Id 
                    LEFT JOIN AspNetRoles ON AspNetRoles.Id = AspNetUserRoles.RoleId
                    WHERE AspNetUsers.Id = @Id";
        var idParam = new SqlParameter("Id", theUserId);
    
        var result = context.Database.ExecuteQuery(sql, idParam);
    }
    

    Pretty simple!

    If you alias your SQL return columns:

    SELECT AspNetUSers.UserName, AspNetRoles.Name As RoleName
    

    Then your DTO class can look like this:

    public class UserWithRole
    {
        public string UserName {get;set;}
        public string RoleName {get;set;}
    }
    

    Which is obviously a lot cleaner.

提交回复
热议问题