locked
Asp.Net Identity: Can't remove user from a role. Is this a bug or ...? RRS feed

  • Question

  • User1517432539 posted

    hi

    The following code adds user to a role ( in other words, RoleManager.Update adds an entry into AspNetUserRoles table )

    var role = RoleManager.FindByName("roleName");
    var user = UserManager.FindById("userName" );
    
    
    IdentityUserRole userRole = new IdentityUserRole();
    userRole.RoleId = role.Id;
    userRole.UserId = user.Id;
    
    role.Users.Add(userRole);
    RoleManager.Update(role); // adds user to a role

     I'd also expect the following code to remove user from a role, but instead nothing happens ( in other words, RoleManager.Update should remove an entry from AspNetUserRoles table, but it doesn't ). Is this a bug or ...?

    var role = RoleManager.FindByName("roleName");
    var user = UserManager.FindById("userName" );
    
     
    IdentityUserRole userRole = new IdentityUserRole();
    userRole.RoleId = role.Id;
    userRole.UserId = user.Id;
    
     
    role.Users.Remove(userRole);
    RoleManager.Update(role); // nothing happens

    Btw:  The following code does remove user from a role:

    UserManager.RemoveFromRole(user.Id, role.Name);

    thank you

    Tuesday, August 12, 2014 12:50 PM

Answers

  • User714605668 posted

    Suppose this is by design.

    I found an ASP.NET 2.0 article:

    http://msdn.microsoft.com/en-us/library/ff647401.aspx

    It told us how to use Role Manager in ASP.NET 2.0, there is a similar way to remove user:

    // Example 1 - Add one user to one role
    Roles.RemoveUserFromRole("TestOne", "ExampleRole1");
    
    // Example 2 - Add one user to several roles
    Roles.RemoveUserFromRoles("TestTwo", 
      new string[] { "ExampleRole1", "ExampleRole2" });
    
    // Example 3 - Add several users to one roles
    Roles.RemoveUsersFromRole(
      new string[] { "TestTwo", "TestThree" }, "ExampleRole3");
    
    // Example 4 - Add several users to several roles
    Roles.RemoveUsersFromRoles(
      new string[] { "TestThree", "TestFour" }, 
      new string[] { "ExampleRole4" }); 
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 14, 2014 3:05 AM