Search code examples
c#asp.net-mvcentity-frameworkentity-framework-6asp.net-identity

Asp.net identity What linq query can I write to return all users with their roles including users without role?


I want to get all users with their roles grouped by their name, and also include users that don't have any role.

I am using asp.net identity 2 so far i have tried

from user in users
from identityUserRole in user.Roles
join identityRole in identityRole on identityUserRole.RoleId equals identityRole.Id into r
from roles in r
group roles.Name by user.UserName into g
select new
{
    UserName = g.Key,
    Roles = g.ToList()
};

But this return only users that have role..


Solution

  • I prefer to use a model to map data:

    public class UserDto
    {
        public string UserName { set; get; }
        public List<string> Roles { set; get; }
    }
    

    and then get all users and their roleNames like this:

    var users = (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 UserDto { UserName = u.UserName, Roles = query.ToList() })
                 .ToList();