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

In my ASP.NET MVC5 Identity 2 application, the application tries to use transactions, but it does not work. See below code that does not work. If var saveteacher = _teacherService.Create(aTeacher); do not insert successfully, then AspNetUsers does not roll back from the database.

the 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); } } } 
+7
asp.net-mvc identity asp.net-identity
source share
3 answers

I think the problem may be asynchronous use.

Try creating a transaction as follows:

 TransactionScope transaction = new TransactionScope(System.Transactions.TransactionScopeAsyncFlowOption.Enabled); 

(you need to add System.Transactions ) to the links.

To complete the transaction, go to transaction.Complete() to roll back do transaction.Dispose() .

+6
source share

The problem is that you are creating a new instance of SchoolMSDbContext when you must purchase an existing one from HttpContext.

Example:

 using (var dataContext = HttpContext.GetOwinContext().Get<ApplicationDbContext>()) { //... } 
+1
source share

Ensure that _teacherService and UserManager use the same database context. No need to create a TransactionScope.

0
source share

All Articles