Domanda

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.

È stato utile?

Soluzione 2

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();

Altri suggerimenti

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();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top