Last active
January 28, 2016 21:36
-
-
Save plioi/b9b319de11af3d9edc36 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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