Skip to content

Instantly share code, notes, and snippets.

@magnusbakken
Created January 8, 2018 13:29
Show Gist options
  • Save magnusbakken/671abb7cf43798cffdb45f29bb839fe1 to your computer and use it in GitHub Desktop.
Save magnusbakken/671abb7cf43798cffdb45f29bb839fe1 to your computer and use it in GitHub Desktop.
Workaround for transactions with Effort for Entity Framework 6
using System;
using System.Data;
using System.Data.Entity;
namespace MyNamespace
{
public partial class MyDbContext : DbContext
{
public bool IsInMemoryTestContext { get; set; }
public IDbContextTransaction BeginTransaction()
{
if (IsInMemoryTestContext)
return new FakeDbContextTransaction();
else
return new WrappedDbContextTransaction(Database.BeginTransaction());
}
public IDbContextTransaction BeginTransaction(IsolationLevel isolationLevel)
{
if (IsInMemoryTestContext)
return new FakeDbContextTransaction();
else
return new WrappedDbContextTransaction(Database.BeginTransaction(isolationLevel));
}
}
public interface IDbContextTransaction : IDisposable
{
void Commit();
void Rollback();
}
internal class FakeDbContextTransaction : IDbContextTransaction
{
public void Commit() { }
public void Dispose() { }
public void Rollback() { }
}
internal class WrappedDbContextTransaction : IDbContextTransaction
{
private readonly DbContextTransaction _dbContextTransaction;
internal WrappedDbContextTransaction(DbContextTransaction dbContextTransaction)
{
_dbContextTransaction = dbContextTransaction;
}
public void Commit() => _dbContextTransaction.Commit();
public void Dispose() => _dbContextTransaction.Dispose();
public void Rollback() => _dbContextTransaction.Rollback();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment