I was wondering today, while playing around, why aren’t my SQL commands, executed within a transaction rolled back, when there is an error. I found out, that in order for this to happen, connection must be opened within the transaction block. Not before. So:
connection.Open();
using(TransactionScope tx = new TransactionScope(TransactionScopeOption.Required)) {
// executed statements here are NOT part of transaction
}
conn.Close();
instead, one must open a connection inside using block. Like so:
using(TransactionScope tx = new TransactionScope(TransactionScopeOption.Required)) {
conn.Open();
// execute statements
conn.Close();
tx.Complete(); // set complete flag in order for transaction to succeed.
}
If you don’t call TransactionScope.Complete() method, the transaction will rolback (when Dispose happens).