asp.net-identity transaction issue

后端 未结 1 1172
温柔的废话
温柔的废话 2021-01-19 02:48

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 sa

1条回答
  •  感情败类
    2021-01-19 03:28

    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.

    0 讨论(0)
提交回复
热议问题