Updated on Kisan Patel
Problem:
How to use Transactions in ASP.NET MVC ?
How to Handle Transactions in ASP.NET MVC ?
How to implement transactions in an application based on MVC4 / Entity Framework (EF)?
Solution:
You need to wrap your database operation within a DbContextTransaction
. See the below code:
using (var transaction = db.Database.BeginTransaction()) { try { // try to execute any database operations } catch (Exception) { // roll back all database operations, if any thing goes wrong transaction.Rollback(); } }
Explanation
Database.BeginTransaction() has two overrides – one which takes an explicit IsolationLevel and one which takes no arguments and uses the default IsolationLevel from the underlying database provider. Both overrides return a DbContextTransaction object which provides Commit()
and Rollback()
methods which perform commit and rollback on the underlying store transaction.
The DbContextTransaction
is meant to be disposed once it has been committed or rolled back. One easy way to accomplish this is the using(…) {…} syntax which will automatically call Dispose() when the using block completes: