Transactions In Entity Framework

In this blog, we will be talking about how transactions take place in Entity Framework.

DbContext.Database.BeginTransaction() method creates a new transaction for the underlying database and allows us to commit or roll back changes made to the database using multiple SaveChanges method calls.

The following example demonstrates creating a new transaction object using BeginTransaction(), which is, then, used with multiple SaveChanges() calls.

  1. using(var context = new SchoolContext()) {  
  2.     using(DbContextTransaction transaction = context.Database.BeginTransaction()) {  
  3.         try {  
  4.             var standard = context.Standards.Add(new Standard() {  
  5.                 StandardName = "1st Grade"  
  6.             });  
  7.             context.Students.Add(new Student() {  
  8.                 FirstName = "Rama2",  
  9.                     StandardId = standard.StandardId  
  10.             });  
  11.             context.SaveChanges();  
  12.             context.Courses.Add(new Course() {  
  13.                 CourseName = "Computer Science"  
  14.             });  
  15.             context.SaveChanges();  
  16.             transaction.Commit(); //save the changes  
  17.         } catch (Exception ex) {  
  18.             transaction.Rollback(); //rollback the changes on exception  
  19.             Console.WriteLine("Error occurred.");  
  20.         }  
  21.     }  
  22. }  

In the above example, we created new entities - Standard, Student, and Course and saved these to the database by calling two SaveChanges(), which execute INSERT commands within one transaction.

If an exception occurs, then the whole changes made to the database will be rolled back.

I hope it's helpful.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now