8

I am not clear on whether I need to use TransactionScope or DbContext.SaveChanges() is enough to commit my transaction consisting of multiple CRUD operations. I am using SQL Server in the backend.

Jas
  • 516
  • 1
  • 6
  • 13

1 Answers1

13

If you are calling SaveChanges() multiple times, and want to roll back all of those changes, yes you would want to use a TransactionScope. If you are calling SaveChanges() once on the context, all your changes are pushed to the database at once in a transaction behind the scenes.

Steven V
  • 16,357
  • 3
  • 63
  • 76
  • Just a confirmation required for the following scenario:In case I call SaveChanges() one time for multiple CRUD operations, I have to dispose the DbContext object to rollback the transaction. – Jas Jun 25 '13 at 15:48
  • I don't think disposing of the `DbContext` will roll back the transaction. If that's the case you probably want to look in the overload options for `SaveChanges()` which you can disable the automatic commit of the transaction and you would be in charge of calling `AcceptAllChanges()`. http://msdn.microsoft.com/en-us/library/bb739065.aspx – Steven V Jun 25 '13 at 15:59
  • But the msdn link that you provided says that ObjectContext.SaveChanges() api is now obsolete. Also, will the ObjectContext.SaveChanges() rollback the entire transaction in case of an exception thrown by SQL Server. Also, is there not any simpler way to rollback my CRUD operations using DbContext? – Jas Jun 25 '13 at 16:07
  • At that point either use the new overload [`SaveChanges(SaveOptions options)`](http://msdn.microsoft.com/en-us/library/dd395500.aspx), but that doesn't seem to fit what you're trying to accomplish with the least code. In that case, rolling your own `TransactionScope` maybe the easiest thing. – Steven V Jun 25 '13 at 16:12
  • Since disposing the TransactionScope object without calling transactionScope.Complete() rolls-back the transaction, should it not work the same way for DbContext, I mean, disposing DbContext object without calling it's SaveChanges() method should ideally rollback the transaction. I am not sure on this, but just need more information on why it's not the same as TransactionScope rollback. – Jas Jun 25 '13 at 16:24
  • I guess it does, but a transaction is a database function, not a C# function. So if you create a `DbContext` without calling `SaveChanges` you've done nothing with the database/transaction. You've just added objects to a entity in C#. When you start a transaction scope, it translates to `BEGIN TRANSACTION` in SQL. When you dispose the `TransactionScope` it runs `ROLLBACK TRANSACTION` in SQL. And if you use `TransactionScope.Complete()` it runs `COMMIT TRANSACTION`. – Steven V Jun 25 '13 at 17:15
  • Thanks a bunch for all the clarifications Steven – Jas Jun 25 '13 at 19:21