简体   繁体   中英

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?

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 I dentityRole<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM