Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does all code inside TransactionScope block not really executed until scope is committed or rollbacked?

I've read about TransactionScope and this article, but I still don't understand 2 things:

  1. When SqlCommand.ExecuteNonQuery is executed it doesn't really executed until scope.Complete() is invoked? If it's true, so where all the operations that were executed within the scope are remain and wait for scope.Complete() or scope.Rollback()?
  2. When TransactionScope is instantiated how it prevents from SqlCommand.ExecuteNonQuery to be executed and wait for scope.Complete() or scope.Rollback()? Does it creates some "place" and SqlCommand somehow knows about it and puts the instructions in there?
like image 544
theateist Avatar asked Jul 19 '12 10:07

theateist


1 Answers

[1] When SqlCommand.ExecuteNonQuery is executed it doesn't really executed until scope.Complete() is invoked?

No this is not correct. Your command is executed on the line where you call ExecuteNonQuery. It is, however, interesting to know where all the changes are stored. The changes do not go directly to the affected table(s) on the server side, rather the changes are stored in a temporary place (again on a server side), which leads to an answer on your second question

[2] When TransactionScope is instantiated how it prevents from SqlCommand.ExecuteNonQuery to be executed and wait for scope.Complete() or scope.Rollback()?

It does not prevent as such, the action is executed, but because the result of the action is stored in a temporary location you must either merge these changes with the main table(s) - scope.Commit() or discard these changes - scope.Rollback() (or whatever is used to discard the changes in the specific database data provider)

like image 141
oleksii Avatar answered Nov 14 '22 21:11

oleksii