36

Entity Framework 6 introduced a new way to support transactions in the DbContext with the BeginTransaction method:

var db = new MyDbContext();
using(var tx = db.Database.BeginTransaction())
{
    // update entities
    try
    {
        db.SaveChanges();
        tx.Commit();
    }
    catch(Exception)
    {
        tx.Rollback();
    }
}

Is the Rollback() call in the method necessary? What happens if it is not called on an exception? I know when using TransactionScope it will roll back the transaction automatically when it is disposed and Complete is not called. Does DbContextTransaction behave similarly?

Dismissile
  • 32,564
  • 38
  • 174
  • 263

2 Answers2

51

No it is not necessary to explicitly call Rollback. The tx variable will be disposed when the using block finishes, and the transaction will be rolled-back if Commit() has not been called.

I have tested this using SQL Server Activity Monitor, by observing the locks held on the database objects, as well as querying against the database to observe when the data is rolled back, using the nolock hint in my select statement to be able to view uncommitted changes in the database.
E.g. select top 10 * from [tablename] (nolock) order by modifiedDate

Teevus
  • 1,104
  • 1
  • 10
  • 23
  • 7
    I did tests and got the same result but I didn't find any documentation related to rollbacking the transaction on disposing. – Akira Yamamoto Oct 02 '14 at 20:32
  • I know this post a bit old but there is now a documentation for that: https://learn.microsoft.com/en-us/ef/core/saving/transactions and it confirms this answer – E-A Jun 12 '22 at 16:32
4

To the EF, the database provider is arbitrary and pluggable and the provider can be replaced with MySQL or any other database that has an EF provider implementation. Therefore, from the EF point of view, there is no guarantee that the provider will automatically rollback the disposed transaction, because the EF does not know about the implementation of the database provider.

This answer pretty much explains everything and confusion with all msdn docs having that Rollback called explicitly: https://stackoverflow.com/a/28915506/5867244

Grigoryants Artem
  • 1,401
  • 2
  • 15
  • 32