10

I have a command service class, which utilises the unit of work pattern, with various methods to update a database (SQL Azure, in this case) via entity framework.

The command service gets instantiated with a reference to an instance of a dbcontext, whose lifetime is managed by my DI framework of choice.

Some of the command service class' methods wraps multiple updates to the database within a transaction, for example:

public void UpdateStuff(someEntity)
{
    using(var tx = _db.Database.BeginTransaction())
    {
        //Some updates to db
        _db.SaveChanges();
        //Some other updates to db
        _db.SaveChanges();
        tx.Commit();
    }
}

Now, some of these methods calls other methods of the command class from within their transactions, for instance:

public void UpdateWithSomeCascadingStuff(someOtherEntity)
{
    using(var tx = _db.Database.BeginTransaction())
    {
        //Some updates to db
        _db.SaveChanges();

        //Some other cascading logic and updates to db
        var relatedEntityToUpdate = _query.GetSomeEntityToUpdate(someOtherEntity);
        UpdateStuff(relatedEntityToUpdate);
        _db.SaveChanges();
        tx.Commit();
    }
}

Clearly, by doing this, I am nesting EF transactions for the same DbContext instance.

Is this supported and will it cause any trouble? Are there any alternative approaches I can take?

UPDATE: I am using EF6 Code First

2 Answers 2

3

EntityFramework's DBContexts implements both UnitOfWork and Repository patterns in itself.

The context in EF6 also automatically wraps all commits in a transaction in itself (if it is not already part of one).

So, no, you should not share a context between multiple units of work. They should each get their own.

UPDATE

If you try to start duplicate transactions on the same DbContext you get:

An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll

Additional information: The connection is already in a transaction and cannot participate in another transaction. EntityClient does not support parallel transactions.

So no, you can't do what you are asking for.

7
  • Thanks, but this does not answer my question.
    – CShark
    May 13, 2016 at 15:09
  • 1
    EF is hidden behind an interface from client code (as I need to be able to easily swop out storage mechanisms without affecting client code), and also have some CQRS going on. As such I had to "wrap" its UOW implementation. The how, why and correctness of this is a too long discussion. I am aware that EF wraps instructions before SaveChanges in a single transaction. In my scenario, I have mutliple SaveChanges calls that I need to wrap in a single transaction. Once again - not here to defend the design - I just want to find out if I can nest EF6 transactions inside one another.
    – CShark
    May 13, 2016 at 15:15
  • 1
    I've expanded my answer. Hope that helps answer your question better May 13, 2016 at 16:05
  • 1
    I just realized you can solve the "problem" with TransactionScope (using System.Transaction). If you wrap each DbContext inside its own using (var ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { } instead of using BeginTransaction() they can complete their tasks regardless of being inside anoter TS. Setting option to Required enlists in existing scopes or creates a new if none exists. May 13, 2016 at 16:29
  • 2
    That's the second post on this thread that got "RequiresNew" backwards. You cannot nest transaction scopes with "RequiresNew". RequiresNew will throw an error if doesn't create a new ambient transaction (i.e. there's already one active). Use 'Required', because it will either create a new one, or use the existing one if one already exists.
    – Triynko
    May 4, 2018 at 18:04
0

In EF Core 5 there is new feature: Savepoints

You can add Savepoints with in the exited trunsaction and roolback to them:

SavePoints

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.