Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking role exists for user before add

I am trying to add roles for user but before that i want to check it is exists or not. How Can i do that? Here is my code

  public void AddRoleForUser(ApplicationUser obj, IdentityRole role)
    {
        _userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(_context));

        var currentUser = _userManager.FindById(obj.Id);
        // before this i have to check 
        var roleresult = _userManager.AddToRole(currentUser.Id, role.Name);
    }

for example i have a user and its id =1. When i add role for this user i want to check there is a role for this user before add new role to this user

like image 839
Fatikhan Gasimov Avatar asked Oct 30 '25 20:10

Fatikhan Gasimov


1 Answers

You just need to check User.IsInRole("YourRoleName");

If you want to check by User Id, use the code below.

if (!userManager.IsInRole(user.Id, "Admin"))
{
    userManager.AddToRole(user.Id, "Admin");
}
like image 104
Basanta Matia Avatar answered Nov 02 '25 11:11

Basanta Matia