MVC 5 Entity Framework 6 Getting all user in a role

asp.net-identity asp.net-mvc-5 entity-framework-6

Question

This should be really simple and quick and I don't know if its because I'm having a brain dead moment or just missing something obvious but here is the question.

All I want to do is get a list of the users who are in a certain role. For example I want the user Id's of all the users in the "Customer" role. How do I achieve this?

I've tried getting the Id of the role I want to check against but I can't seem to query on the AspNetUserRoles table.

Any help would be gratefully recieved.

PS. Forgot to mention this is for a backend site accessing the front end DB database first model. So using the ApplicationDbContext() wouldn't work.

1
1
4/21/2014 12:52:44 PM

Accepted Answer

Ok so it was a brain dead moment all I needed to do was the following:

var customers = db.AspNetUsers
                  .Where(u => u.AspNetRoles.Any(r => r.Name == "Customer") && 
                              u.IsActivated == true && u.IsClosed == false && 
                              u.IsPaused == false && u.IsSuspended == false)
                  .ToList();
2
4/22/2014 7:48:26 PM

Popular Answer

You can reach the AspNetUserRoles table and AspNetRoles table via the User DbSet on the context...

using(var context = new ApplicationDbContext()) 
{
    var customers = context.Users
                        .Where(u => u.Roles.Any(r => r.Role.Name == "Customer"))
                        .ToList();
}


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