Here's my code to change user's roles in ASP.NET Core Identity:
public void UpdateRoles(long userId, List<string> roles)
{
var user = userManager.FindByIdAsync(userId.ToString()).Result;
var existingRoles = userManager.GetRolesAsync(user).Result.ToList();
var newRoles = roles.Where(i => !existingRoles.Contains(i)).ToList();
var rolesToBeDeleted = existingRoles.Where(i => !roles.Contains(i)).ToList();
var result = userManager.RemoveFromRolesAsync(user, rolesToBeDeleted).Result;
if (!result.Succeeded)
{
throw new Exception($"Error managing roles of the user. ${result.Serialize()}");
}
result = userManager.AddToRolesAsync(user, newRoles).Result;
if (!result.Succeeded)
{
throw new Exception($"Error managing roles of the user. ${result.Serialize()}");
}
}
And userManager
is an instance of UserManager<User>
.
This works fine. But as you can see, it's a two-step process. I have to remove roles first, and then add new ones, because ASP.NET Core Identity API does not give me a unified method.
Now I want to do it transactionally. So I tried to use TransactionScope
. But I get this error:
(This connection was used with an ambient transaction. The original ambient transaction needs to be completed before this connection can be used outside of it.)
So, the question is, how can I change user roles, inside a transaction?