How to get all users in Role (Microsoft ASP.NET Identity EntityFramework 2.0.0-beta1)?

I just updated to ASP.NET Identity EntityFramework 2.0.0-beta1 and got a compilation errors for my Roles classes. Maybe somebody can give me some clue how to get all users for a specific Role?

It’s something very close, when I browse with Intellisense I am almost there, but need a tip :-).

This is how it worked before update:

 user.Roles.First().Role.Name.Equals("Admins")

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Its only exposed on the EF implementation layer so:

roleManager.FindByName("Admins").Users

Method 2

The accepted answer returns CustomUserRoles. If you are looking for the list of ApplicationUsers, try:

public IList<ApplicationUser> GetApplicationUsersInRole(string roleName)
{
    var selectedUserIds = from role in roleManager.Roles
                          where role.Name == roleName
                          from user in role.Users
                          select user.UserId;
    // this _users comes from the ApplicationDbContext.ApplicationUser
    return _users.Where(applicationUser => selectedUserIds.Contains(applicationUser.Id)).ToList();
}

Method 3

I really liked VahidN’s solution, but I modified it a bit. I made it into one query that uses the dbcontext. This allows you to add additional clauses into the query (e.g. deleted, emailconfirmed, etc.)

public IEnumerable<ApplicationUser> GetApplicationUsersInRole(string roleName)
{
      return from role in context.Roles
             where role.Name == roleName
             from userRoles in role.Users
             join user in context.Users
             on userRoles.UserId equals user.Id
             where user.EmailConfirmed == true
               && user.IsDeleted == false
             select user;
 }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x