Cos Callis
Cos Callis

Reputation: 5084

Asp.Net Identity 2.0 Return Roles (By NAME) with a LIST of Users

I fear I must be missing something simple, but when I execute:

var results = UserManager.Users.Where(u => u.mgr == appUser.org || appUser.org == "corp");

I get a IQueryable collection of ApplicationUsers which match my requirements... except... each ApplicationUser in the set has a property (collection) of Roles which only includes the UserId & RoleId and NOT the name of the role. I'm to believe that adding a .Include("???") to this linq query should allow me to bring the names of the roles back with each user... but I can not find the right expression to get there.

How may I retrieve the names of the roles each user in the set is assigned?

Upvotes: 1

Views: 2134

Answers (1)

Adil Mammadov
Adil Mammadov

Reputation: 8676

In ASP.NET Identity Roles property of ApplicationUser is ApplicationUserRole. This table is many-to-many relationship between ApplicationUsers and ApplicationRoles. If you want to get other details of reles, you have to use Include as you stated yourself:

var results = UserManager
    .Users
    .Where(u => u.mgr == appUser.org || appUser.org == "corp")
    .Include(m => m.Roles.Select(r => r.Role));

As @GeoffJames notes, you have to add using System.Data.Entity; to your using list.

Update

Generally your custom Identity models should be as below:

public class ApplicationUserRole : IdentityUserRole
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

ApplicationRole should inherit IdentityRole<string, ApplicationUserRole>

public class ApplicationRole 
: IdentityRole<string, ApplicationUserRole>
{
}

ApplicationUser should inherit IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>

public class ApplicationUser 
    : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    .............
}

You can also see my answer here, it may help.

Upvotes: 3

Related Questions