Skip to content

Instantly share code, notes, and snippets.

@plioi
Last active January 28, 2016 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plioi/dbf6cab74aac2c6ee767 to your computer and use it in GitHub Desktop.
Save plioi/dbf6cab74aac2c6ee767 to your computer and use it in GitHub Desktop.
public class ContactsContext : DbContext
{
private DbContextTransaction _currentTransaction;
...
public void BeginTransaction()
{
if (_currentTransaction != null)
return;
_currentTransaction = Database.BeginTransaction(IsolationLevel.ReadCommitted);
}
public void CloseTransaction()
{
CloseTransaction(exception: null);
}
public void CloseTransaction(Exception exception)
{
try
{
if (_currentTransaction != null && exception != null)
{
_currentTransaction.Rollback();
return;
}
SaveChanges();
_currentTransaction?.Commit();
}
catch (Exception)
{
if (_currentTransaction?.UnderlyingTransaction.Connection != null)
_currentTransaction.Rollback();
throw;
}
finally
{
_currentTransaction?.Dispose();
_currentTransaction = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment