Search code examples
c#asp.netasp.net-mvcentity-frameworkasp.net-identity-2

ASP.Net MVC List of User and their Roles


I'm using ASP.NET MVC Default project. In there we have a database called AspNetRoles (defines roles like Admin, User)
Role Database

then there's a database called AspNetUsers which just defines Users when you register them User Database

and the last and most important is AspNetUserRoles. When you assign Roles to the User here is where it is placed (and the Id's are hashed)

UserRole Database

My question is, how do I get a list of every user on the system and their roles? I can't figure out how to start doing this. Should I create my own User and Role database and forget about the default one? Or is there a way of creating with the default ones?


Also, I would keep in mind that as of now I'm assigning Roles when registering (User by default) and later when I create the Index where I show the list of Users and Roles, I will want to edit them, but this is just a disclaimer. Thank you very much for any type of help.


Solution

  • There are no built in methods for retrieving the list of users with their roles so you can try to get the user and their role like below (using EF):

    var list = context.Users        
        .Where(x => x.Roles.Select(a => a.Id))
        .ToList();
    

    Using this you get every users and assigned roles.

    Update Create a Model like below first:

    public class UserRoleInfo
    {
        public ApplicationUser User { set; get; }
        public List<string> Roles { set; get; } 
    }
    

    Then Your Query would be like (Query Syntax):

    var listOfUsers = (from u in db.Users
                 let query = (from ur in db.Set<IdentityUserRole>()
                              where ur.UserId.Equals(u.Id)
                              join r in db.Roles on ur.RoleId equals r.Id select r.Name)
                              select new UserRoleInfo() {User = u, Roles = query.ToList<string>()})
                             .ToList();
    

    Query above will return Every User With their Roles no matter how many.

    UPDATE

    Your view would be like:

    @model UserRoleInfo
        <table>
            <tbody>
    @foreach (var user in Model)
    {
        var appUser = user.ApplicationUser;
        var roles = user.Roles;
    
                <tr>
                    <td>
                        @appUser.Email
                    </td>
                    <td>
                        @string.Join(",", roles)
                    </td>
                </tr>
    
    }
            </tbody>
        </table>