5

How can I get a list of users including the role name per user? My app has the default tables of an MVC Project.

I'm able to retrieve all users using Identity 2.1 like this:

Model

public class GetVendorViewModel
{
    public IList<ApplicationUser> Vendors { get; set; }
}

Controller

public ActionResult Index()
        {

            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var roleStore = new RoleStore<IdentityRole>(ac);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
            var vendor = roleManager.FindByName("Vendor").Users;
            var model = new GetVendorViewModel { Vendors = vendor };
            return View("~/Views/User/Administrator/Vendor/Index.cshtml", model);
        }

Right now is returning this:

[
   {
      UserId: "4f9ed316-a852-45a9-93a8-a337a37b1c74",
      RoleId: "a17bb59c-285a-43f9-b5ad-65f46f94bb4f"
   }
]

This is correct but I need to display the user information such as name, email, username etc.

I would like to return a json object like this:

[
  {
    UserId: "4f9ed316-a852-45a9-93a8-a337a37b1c74",
    RoleId: "a17bb59c-285a-43f9-b5ad-65f46f94bb4f"
    RoleName: "Administrator"
    User: {
            name:"Joe Doe",
            email:"jd@mail.com",
            ...
          }
  },
  {
    ...
  }
]

RoleName is in the table AspNetRoles.

UserId and RoleId its being query from AspNetUserRoles.

Any clues?

DavidH
  • 63
  • 1
  • 4

1 Answers1

13

The UserManager stuff in Identity tends to confuse people. Ultimately, users are still just a DbSet on your context, so you can use your context like querying for any other object:

var role = db.Roles.SingleOrDefault(m => m.Name == "role");
var usersInRole = db.Users.Where(m => m.Roles.Any(r => r.RoleId == role.Id));

EDIT Forgot that IdentityUser.Roles references IdentityUserRole instead of IdentityRole directly. So you need to get the role first, and then use the role's id to query into your users.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 3
    I'd also recommend extending the UserManager to encapsulate this method. – Erik Philips Nov 12 '14 at 20:00
  • Good idea. If this is something you tend to use with any frequency, definitely extend `UserManager`. – Chris Pratt Nov 12 '14 at 20:03
  • Chist Pratt, thank you. You suggestion worked perfectly. I'm new to ASP.net MVC 5 Its silly to think that I spent almost all day searching for an answer to something so simple. Thank you again. – DavidH Nov 12 '14 at 20:15
  • 1
    Good solution but we're using this to send notification to admins whenever an unapproved comment is posted. Isn't there a better solution in terms of performance? (Without caching of course) – SepehrM Jun 05 '16 at 07:28