Entity Framework - Transaction


In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete the database, the framework will wrap that operation in a transaction. When you invoke SaveChanges, the context automatically starts a transaction and commits or rolls it back depending on whether the persistence succeeded.

  • This is all transparent to you, and you’ll never need to deal with it.

  • This transaction lasts only long enough to execute the operation and then completes.

  • When you execute another such operation, a new transaction starts.

Entity Framework 6 provides the following −

Database.BeginTransaction()

  • It is a simple and easier method within an existing DbContext to start and complete transactions for users.

  • It allows several operations to be combined within the same transaction and hence either all are committed or all are rolled back as one.

  • It also allows the user to more easily specify the isolation level for the transaction.

Database.UseTransaction()

  • It allows the DbContext to use a transaction, which was started outside of the Entity Framework.

Let’s take a look into the following example where multiple operations are performed in a single transaction. The code is as −

class Program {

   static void Main(string[] args) {

      using (var context = new UniContextEntities()) {

         using (var dbContextTransaction = context.Database.BeginTransaction()) {

            try {

               Student student = new Student() {
                  ID = 200, 
                  FirstMidName = "Ali", 
                  LastName = "Khan", 
                  EnrollmentDate = DateTime.Parse("2015-12-1")
               };

               context.Students.Add(student);

               context.Database.ExecuteSqlCommand(@"UPDATE Course SET Title = 
                  'Calculus'" + "WHERE CourseID = 1045");

               var query = context.Courses.Where(c ⇒ c.CourseID == 1045);

               foreach (var item in query) {
                  Console.WriteLine(item.CourseID.ToString()
                     + " " + item.Title + " " + item.Credits);
               }

               context.SaveChanges();
               var query1 = context.Students.Where(s ⇒ s.ID == 200);

               foreach (var item in query1) {
                  Console.WriteLine(item.ID.ToString() 
                     + " " + item.FirstMidName + " " + item.LastName);
               }

               dbContextTransaction.Commit();
            } catch (Exception) {
               dbContextTransaction.Rollback();
            }

         }
      }
   }
}
  • Beginning a transaction requires that the underlying store connection is open.

  • So calling Database.BeginTransaction() will open the connection, if it is not already opened.

  • If DbContextTransaction opened the connection then it will close it when Dispose() is called.

Advertisements