0

I am trying to use transactions with EF4 Code-first with an unit of work implementation. Is there a reason we cannot use Connection.BeginTransaction from the context ? It is only intended to be used in SQL transactions only ? Because when im calling it i get the error : Illegal operation. Connection is closed.

Thanks.

Rushino
  • 9,415
  • 16
  • 53
  • 93

1 Answers1

2

Part of the answer will be that DbContext.SaveChanges() is automatically transactional, so in many cases, you will not need to roll your own transactions. What is your scenario, and why do you think that you need to manually do transactions?

If you decide you need them, wrap SaveChanges in a transaction:

    using (TransactionScope transaction = new TransactionScope())
    {
        context.SaveChanges();
    }

If you run Profiler, you will note that the transaction is rolled back once you leave the using{} block. To commit your transaction, call transaction.Complete(); after SaveChanges().

anon
  • 4,578
  • 3
  • 35
  • 54
  • I think that i need to do manual transaction because there no mechanism that actually rollback the changes done to the context before the SaveChanges() (Correct me if i am wrong). What happen if an exception occurs ? When you say "you will note that the transaction is rolled back once you leave the using{} block" did you mean when an exception would occur ? – Rushino Feb 09 '11 at 12:32
  • Does it rollback all changes in database if transaction not complete? – Sepehr Estaki Jan 07 '20 at 11:55
  • or should I replace it with something like this: `using (TransactionScope s = context.Connection.BeginTransaction())` – Sepehr Estaki Jan 07 '20 at 12:15