In My ASP.NET MVC5 Identity 2 Application trying to use transactions but it is not working.please see the below code the transactions not working.If var saveteacher = _teacherService.Create(aTeacher); not insert successfully then AspNetUsers not rollback from database.
Code:
using (var  dataContext = new SchoolMSDbContext())
{
  using (var trans = dataContext.Database.BeginTransaction(IsolationLevel.ReadCommitted))
  {
    try
    {
      var adminresult =await UserManager.CreateAsync(user, teacherViewModel.Password);
      if (adminresult.Succeeded)
      {
        aTeacher.Id = user.Id;
        var saveteacher = _teacherService.Create(aTeacher);
      }
      else
      {
        trans.Rollback();
        ModelState.AddModelError("", adminresult.Errors.First());
        return View();
      }
      trans.Commit();
    }
    catch (Exception ex)
    {
      trans.Rollback();
      Console.WriteLine(ex.InnerException);
    }
  }
}
                I think the problem could be with async stuff.
Try creating the transaction like this:
TransactionScope transaction = new TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled);
(you'll have to add System.Transactions) to references.
To commit transaction go transaction.Complete() to rollback do transaction.Dispose().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With