简体   繁体   中英

Retrieve Role for a User in the DAL using ASP.NET Identity

I have a bog-standard implementation of Users and Roles using ASP.NET Identity:

public class User : IdentityUserBase { }
public class Role : IdentityRoleBase { }
public class UserRole : IdentityUserRoleBase { }

I need a property or method in the User class that returns the (first) role of the user (in my app, each user can only have one):

public class User : IdentityUserBase
{
  // ...
  public Role GetRole()
  {
    return this.Roles.FirstOrDefault(); // this actually returns a UserRole object, with only a UserId and a RoleId available (no Role object)
  }
}

Is there a way to do this here in the DAL?

I know it's possible at the UI layer using global objects like RoleManager, DbContext or HTTPContext but I don't have access to those in the User class (and don't want to have to pass them in as arguments).

I would have thought that this must be a standard use-case but I can't find an answer ... my question is basically the same as this one but I need access to the Role information within the User object itself.

First of all, you shouldn't put the GetRole method in the User class, keep those models simple and clean.

To get the roles for a user, you need the db context and the user ID, and you can do this:

var userId = ...; //Get the User ID from somewhere

var roles = context.Roles
    .Where(r => r.Users.Any(u => u.UserId == userId))
    .ToList();

This worked:

public class UserRole : IdentityUserRoleBase
{
    public virtual Role Role { get; set; } // add this to see roles
    public virtual User User { get; set; } // add this to see users
}

The User and Role properties are now exposed through the UserRole property that is available through the User object.

Looking back through the evolution of ASP.NET Identity here , these properties were present in IdentityUserRole by default in version 1 but then removed in version 2 in order to support generic primary keys, with a recommendation to use the UserManager class. However, this doesn't help cases like mine where the operations need to be done in the DAL and don't have easy access to this class (or the any of the context classes). Given that I will never have any other type of primary key, it feels quite safe to do this.

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