DB Transactions

Combining several operations into one transaction within the same context

Starting with EF6 the framework now provides:

Database.BeginTransaction() : An easier method for a user to start and complete transactions themselves within an existing DbContext – allowing several operations to be combined within the same transaction and hence either all committed or all rolled back as one. It also allows the user to more easily specify the isolation level for the transaction.

Database.UseTransaction() : which allows the DbContext to use a transaction which was started outside of the Entity Framework.

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.

You can read more here: https://docs.microsoft.com/en-us/ef/ef6/saving/transactions

Example from DTML code:

  using (var dbContextTransaction = db.Database.BeginTransaction(IsolationLevel.ReadCommitted))
    {
      try
        {
           // First SQL operation
           int data = await db.Database.ExecuteSqlCommandAsync(..);

                            if (data > 0)
                            {
                            // Another SQL operation
                            await db.Database.ExecuteSqlCommandAsync(..);
                            }
                            else
                            {
                                response.isError = true;
                                response.message = Resources.Resources.StudentAlreadyAddedinClass;
                            }
                           
                        }
       catch (Exception ex)
       {
                            _logger.Error($"$ValidStudentsForClass {ex.Message}");
                            response.isError = true;
                            response.message = Resources.Resources.ErrorOccurred;
                            dbContextTransaction.Rollback();
         }
       }

Last updated