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 =
var userManager =
using (var transaction = dbContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
{
try
{
var user =
var userCreateResult = await userManger.CreateAsync(user, password);
if(!userCreateResult.Succeeded)
{
transaction.Rollback();
return userCreateResult.Errors;
}
var userId = user.Id;
var addToRoleresult = await userManager.AddToRoleAsync(user.Id, "My Role Name");
if(!addToRoleresult.Succeeded)
{
transaction.Rollback();
return addToRoleresult.Errors;
}
transaction.Commit();
}
catch (Exception exception)
{
transaction.Rollback();
throw;
}
}
Hope this helps.
source
share