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
Get all the users from 开发者_开发技巧DB and do a check in code
Go directly to the db and sidestep the role provider
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)
);
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)
);
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
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.
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);
精彩评论