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

不问归期 提交于 2020-01-16 18:44:11

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/48771077/retrieve-role-for-a-user-in-the-dal-using-asp-net-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!