asp.net-identity transaction issue

2019-02-22 23:07发布

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?

1条回答
女痞
2楼-- · 2019-02-22 23:26

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.

查看更多
登录 后发表回答