2

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?

Ali EXE
  • 853
  • 1
  • 7
  • 21
  • How are you doing the transaction? can you post more code? – antoprd Nov 21 '21 at 12:45
  • Try this: https://stackoverflow.com/a/37451850/12100772 Also, if you use sql provider - just for test try to remove `sqlServerOptions` if you have any - in your database configuration, typically in `startup.cs` - it could be that those settings are messing with new transaction. – quain Nov 21 '21 at 16:15

0 Answers0