Mr. Flibble
Mr. Flibble

Reputation: 27003

How to get users not in role,

Is there any reasonably efficient way to get a list of users who are not in a specific role?

The only methods I can see are

  1. Get all the users from DB and do a check in code

  2. Go directly to the db and sidestep the role provider

Upvotes: 5

Views: 2226

Answers (5)

Don Thomas Boyle
Don Thomas Boyle

Reputation: 3045

Found this way, hope this helps others aswell. Very easy.

 var usernames = Roles.GetUsersInRole("Administrator");

            var adminUsers = db.UserProfiles
                 .Where(x => !usernames.Contains(x.UserName)).ToList();
            return View(adminUsers);

Upvotes: 1

Arun K Kotte
Arun K Kotte

Reputation: 41

Changing the Select to Where in the code provided by Alex will actually return the results instead of just true/false.

var usersInRole = Roles.GetUsersInRole("admin");
var users = Membership.GetAllUsers()
    .Cast<MembershipUser>()
    .Where(u => 
        !usersInRole.Contains(u.UserName)
    );

Upvotes: 4

Oleks
Oleks

Reputation: 32323

You could just get the all user list and extract users in role specified from the list:

var usersInRole = Roles.GetUsersInRole("admin");
var users = Membership.GetAllUsers()
    .Cast<MembershipUser>()
    .Select(u => 
        !usersInRole.Contains(u.UserName)
    );

Upvotes: 4

Robert
Robert

Reputation: 3302

Another way is to extend RoleProvider with the method GetUsersNotInRole() and query the DB there. You can also combine RoleProvider.GetUsersInRole() with MembershipProvider.GetAllUsers() and find the difference

Upvotes: 3

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

I don't think that there is anything wrong with by-passing the role provider and querying the database directly. You will definitely get the best performance this way.

Upvotes: 2

Related Questions