title: How to change user roles in a transaction in ASP.NET Core Identity?
body: <p>Here's my code to change user's roles in ASP.NET Core Identity:</p>
  <pre><code>public void UpdateRoles(long userId, List&lt;string&gt; roles)
  {
      var user = userManager.FindByIdAsync(userId.ToString()).Result;
      var existingRoles = userManager.GetRolesAsync(user).Result.ToList();
      var newRoles = roles.Where(i =&gt; !existingRoles.Contains(i)).ToList();
      var rolesToBeDeleted = existingRoles.Where(i =&gt; !roles.Contains(i)).ToList();
  
      var result = userManager.RemoveFromRolesAsync(user, rolesToBeDeleted).Result;
      if (!result.Succeeded)
      {
          throw new Exception($&quot;Error managing roles of the user. ${result.Serialize()}&quot;);
      }
      result = userManager.AddToRolesAsync(user, newRoles).Result;
      if (!result.Succeeded)
      {
          throw new Exception($&quot;Error managing roles of the user. ${result.Serialize()}&quot;);
      }
  }
  </code></pre>
  <p>And <code>userManager</code> is an instance of <code>UserManager&lt;User&gt;</code>.</p>
  <p>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.</p>
  <p>Now I want to do it transactionally. So I tried to use <code>TransactionScope</code>. But I get this error:</p>
  <blockquote>
  <p>(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.)</p>
  </blockquote>
  <p>So, the question is, how can I change user roles, inside a <strong>transaction</strong>?</p>