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

asp.net-identity asp.net-mvc c# entity-framework entity-framework-6

Question

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..

1
2
6/20/2017 9:40:25 AM

Accepted Answer

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();
2
6/20/2017 10:31:01 AM

Popular Answer

You could also simplify your query to this.

var userAndRoles = users.Select(user => new
{
    UserName = user.UserName,
    Roles = roles.Where(role => user.Roles.Any(userRole => userRole.UserId == user.UserId && userRole.RoleId == role.RoleId))
});


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow