Search code examples
asp.net-mvcentity-frameworkasp.net-identity

MVC Identity 2.1 - get a list of users NOT in a particular role


How do I get a list of users that are not in 1 particular role? I am using mvc 5, ef 6, identity 2.1.

To get a list of users in the "Host" role I can do:

var getRole = (from r in db.Roles where r.Name.Contains("Host") select r).FirstOrDefault();
var getHostUsers = db.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(getRole.Id)).ToList();

To get a list of all users I can do:

var getUsers = await db.Users.Where(u => u.Id != currentUser).OrderBy(u => u.FirstName).ToListAsync();

But what I need is a list of all users that are not in the "Host" role (getUsers - getHostUsers).


Solution

  • If you want all users, except those with the Host role you can just do the opposite of what you are doing and add an exclamation mark in the where clause.

    var getRole = (from r in db.Roles where r.Name.Contains("Host") select r).FirstOrDefault();
    var getNotHostUsers = db.Users.Where(x => !x.Roles.Select(y => y.RoleId).Contains(getRole.Id)).ToList();