Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net-identity transaction issue

I want to create a user with a role in the same transaction but i have an issue with the implementation. In order to use the userStore in the transaction and have it not save the changes automatically and ignore my transaction i had to turn off AutoSaveChanges. This makes it so it will wait until i call save changes. This works fine but because the userstore now does not return the userId when i call manager.Create due to this being off I dont have an Id to pass into userManager.AddToRole. Is there any way to add the user i am trying to create to a role within the same transaction?

like image 357
thargan Avatar asked Oct 19 '22 21:10

thargan


1 Answers

If you start your transaction manually, then commit it, everything that was written to DB inside your transaction will be held inside your transaction. And you can rollback that if you want to.

Do something like that:

var dbContext = // get instance of your ApplicationDbContext
var userManager = // get instance of your ApplicationUserManager
using (var transaction = dbContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
{
    try
    {
        var user = // crate your ApplicationUser
        var userCreateResult = await userManger.CreateAsync(user, password);
        if(!userCreateResult.Succeeded)
        {
            // list of errors in userCreateResult.Errors
            transaction.Rollback();
            return userCreateResult.Errors;
        }
        // new Guid for user now saved to user.Id property
        var userId = user.Id;

        var addToRoleresult = await userManager.AddToRoleAsync(user.Id, "My Role Name");
        if(!addToRoleresult.Succeeded)
        {
            // deal with errors
            transaction.Rollback();
            return addToRoleresult.Errors;
        }

        // if we got here, everything worked fine, commit transaction
        transaction.Commit();
    }
    catch (Exception exception)
    {
        transaction.Rollback();
        // log your exception
        throw;
    }
}

Hope this helps.

like image 161
trailmax Avatar answered Oct 29 '22 20:10

trailmax