Monday, September 30, 2013

LINQ to SQL DataContext BeginTransaction

LINQ to SQL supports Transactions, but there is no method directly off of the DataContext to initialize one. Fortunately, that functionality is just a simple extension method away!

public static class DataContextExtensions
{
    public static IDbTransaction BeginTransaction(
        this DataContext dataContext, 
        IsolationLevel isolationLevel = IsolationLevel.Unspecified)
    {
        if (dataContext.Connection.State != ConnectionState.Open)
            dataContext.Connection.Open();
 
        return dataContext.Transaction = dataContext.Connection
            .BeginTransaction(isolationLevel);
    }
}
 
public class TransactionTests
{
    [Fact]
    public void Example()
    {
        using (var dataContext = new FutureSimpleDataContext())
        using (dataContext.BeginTransaction())
        {
            // TODO: Stuff!
        }
    }
}
Shout it

Enjoy!
Tom

No comments:

Post a Comment

Real Time Web Analytics