Reputation: 1641
I have an MVC C# app using Identity 2.0. On a form, I have a mulit-select list of roles to assign a user. In the controller, I call
IdentityResult rc = await userManager.AddToRolesAsync(roleViewModel.UserId, roleViewModel.AssignedRoles);
(where roleViewModel.UserId is a GUID, and roleViewModel.AssignedRoles is a string[].
The problem is that if the user is already assigned to a role, the operation fails with "User already in role." I could iterate through the array and query if the user is already in the role prior to attempting to AddToRole (singular), but I would have thought AddToRoles (plural) would allow me to specify whether to ignore existing membership (I certainly didn't see anything in the online doc).
So, my questions...am I thinking this the wrong way? Is AddToRoles (plural) mainly intended for Create operations, and I have to iterate/AddToRole (singular) for edit/updates? Or is there a better way?
Edit 1:
What about this idea?
IEnumerable<string> rolesToAdd = roleViewModel.AssignedRoles.Except(userManager.GetRoles(roleViewModel.UserId));
IEnumerable<string> rolesToRemove = userManager.GetRoles(roleViewModel.UserId).Except(roleViewModel.AssignedRoles);
IdentityResult rcRemove = await userManager.RemoveFromRolesAsync(roleViewModel.UserId, rolesToRemove.ToArray());
IdentityResult rcAdd = await userManager.AddToRolesAsync(roleViewModel.UserId, rolesToAdd.ToArray());
if (!rcAdd.Succeeded || !rcRemove.Succeeded) { ... }
(Yes I know I could re-write that into two lines, I wrote like this for clarity.)
Upvotes: 0
Views: 1039
Reputation: 13217
Documentation is quite shallow on the topic:
You could write your own (extension) method that does the job for you. Batch the requests and incorporate the use of AddToRole
with previous checking for the user being already in the group. This is not a nice way but a possible work-around.
Upvotes: 1