Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Transactions in ASP.NET MVC identity 2?

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);
    }
  }
}
like image 661
Nazmul Hossain Avatar asked Jan 28 '15 09:01

Nazmul Hossain


1 Answers

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

like image 78
trailmax Avatar answered Oct 11 '22 01:10

trailmax