Jerry Bian
Jerry Bian

Reputation: 4238

TransactionScope with same context

Is it ok for me to write such EntityFramework code for the transactions:

using(var trans = new TransactionScope())
{
    using(var context1 = new MyDbContext())
    {
        context1.AddEntity(...);
        context1.SaveChanges();
    }

    using(var context2 = new MyDbContext())
    {
        context2.UpdateEntity(...);
        context2.SaveChanges();
    }

    trans.Complete();
}

What I want to achieve is put above two operations as one unit (it's just a demo, in real situation, those two are separated by different services, so they cannot reuse the context), any of them fail will rollback.

Are above code enough?

Upvotes: 1

Views: 68

Answers (1)

Maarten
Maarten

Reputation: 22955

As you have written your example, yes it will work.

In your question you mention

in real situation, those two are separated by different services, so

It depends what type of services you mean. If you mean WCF services, then you also need to configure your WCF service correctly. See here and/or here for more information.

Upvotes: 1

Related Questions