Asp.net-identity transaction issue

I want to create a user with a role in the same transaction, but I have an implementation problem. To use userStore in a transaction and not save changes automatically and ignore my transaction, I had to disable AutoSaveChanges. This makes it wait for me to invoke saving changes. This works fine, but since the user store now does not return userId when I call manager.Create because of this does not work. Is there a way to add the user I'm trying to create for a role in a single transaction?

+4
source share
1 answer

If you start the transaction manually, and then commit it, everything that was written to the database inside your transaction will be stored inside your transaction. And you can roll back if you want.

Do something like this:

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.

+3
source

All Articles