Introduction

In this article, we will learn Entity Framework Transactions.

So, Let's get started.

Understanding Transactions

Built-in Transaction Management

C#
using (var context = new AppDbContext())
  {
	 // Operations 
	 context.SaveChanges(); // EF handles transaction automatically
  }

Handling Multiple Operations as a Unit

Transactions are crucial for ensuring data integrity when performing multiple related operations. For instance, transferring money between accounts involves debiting one account and crediting another. Both operations should be part of a single transaction.

Example

C#
using (var context = new AppDbContext())
  {
	 using (var transaction  = context.Database.BeginTransaction()) 
	   {
	     try 
	      {	         
	         // Debit one account
	         // Credit another account 
	        
	         context.SaveChanges();
	         transaction.commit();
	      }
	     catch(Exception ex)
	      {
	        transaction.Rollback();
	        // Handle the exception
	      }
	   }
   }

Rollback Strategies

C#
using (var context = new AppDbContext())
  {
	 using (var transaction  = context.Database.BeginTransaction()) 
	   {
	     try 
	      {
	        // Operations
	        transaction.commit();
	      }
	     catch(Exception ex)
	      {
	        transaction.Rollback();
	      }
	   }
  }

Commit Strategies

C#
using (var context = new AppDbContext())
  {
	 using (var transaction  = context.Database.BeginTransaction()) 
	   {
	     try 
	      {
	        // Operations
	        transaction.commit();
	      }
	     catch(Exception ex)
	      {
	        transaction.Rollback();
            // Log or Handle the exception
	      }
	   }
  }

Combining Explicit Transactions with Multiple Contexts

C#
using (var context1 = new AppDbContext1())
using (var context2 = new AppDbContext2())
 {
	using (var transaction  = context1.Database.BeginTransaction()) 
	 {
  	    try 
  	     {
  	        // Operations on context1
  	        context1.SaveChanges();
  	         
  	        // Operations on context2
  	        context2.Database.UseTransaction(transaction.GetDbTransation());
  	        context2.SaveChanges();
  	         
  	        transaction.commit();
  	     }
  	    catch(Exception ex)
  	     {
  	        transaction.Rollback();
  	     }
     }
 }

Points to be taken

Conclusion

In this article, I have tried to cover how to handle Entity Framework Transactions.