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

Accepted Answer

I like using a model to map the data:

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

then get all users' roleNames as follows:

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

Your inquiry might also be made simpler 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