Skip to content

Instantly share code, notes, and snippets.

@plioi
Last active January 28, 2016 21:36
Show Gist options
  • Save plioi/b9b319de11af3d9edc36 to your computer and use it in GitHub Desktop.
Save plioi/b9b319de11af3d9edc36 to your computer and use it in GitHub Desktop.
public class ExampleDbContext : 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