Skip to content

Instantly share code, notes, and snippets.

@plioi plioi/ExampleDbContext.cs
Last active Jan 28, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.