Reputation: 33071
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?
Upvotes: 37
Views: 7637
Reputation: 1621
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
Upvotes: 4
Reputation: 1124
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
Upvotes: 52