Skip to content

Instantly share code, notes, and snippets.

@artiomchi
Created January 16, 2014 14:45
Show Gist options
  • Save artiomchi/8456090 to your computer and use it in GitHub Desktop.
Save artiomchi/8456090 to your computer and use it in GitHub Desktop.
/// <summary>
/// Controls SQL transactions for a Linq Data Context.
/// Unfortunately the implementation provided by .NET does'nt work properly (transaction state isn't reset to default after using it)
/// Note: Don't trust the profiler. Even though the results show that this class doesn't work properly - it seems to work just fine!
/// </summary>
public class TransactionBroker : IDisposable
{
private DataContext _context;
public TransactionBroker(DataContext context)
: this(context, IsolationLevel.ReadCommitted) { }
public TransactionBroker(DataContext context, IsolationLevel isolationLevel)
{
if (context == null)
throw new NullReferenceException("context");
_context = context;
if (context.Connection.State != System.Data.ConnectionState.Open)
context.Connection.Open();
context.Transaction = context.Connection.BeginTransaction(isolationLevel);
}
public void Dispose()
{
_context.Transaction.Dispose();
// Because of a bug in .NET (seems like it's there since .NET 1.1!!!) we have to reset the transaction level back to the defaults
using (_context.Connection.BeginTransaction()) { }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment