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
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.