TransactionScope Usage

Emre Erkoca
1 min readApr 23, 2021

We suppose you have customers and your customers can share some posts in your system. When a user clicks to the “Delete My Account” button you should delete her/his posts and after delete account information.

When deleting post-operation processing it might get an error. Then it should roll back the operation. Because it might get an error (e.g: Posts couldn’t found) when it’s processing again. Also, when you want to do two operations (delete posts and delete account information) in the same block if you get an error while processing the second operation it should rollback. You can ensure this with TransactionScope.

I created a sample of this. It has two database operations. Firstly you can read the code block. After I’ll explain.

I used AdventureWorks2012 database and I made two database operations. updatePersonPhoneSqlCommand updates person’s phone. updatePersonSqlCommand updates person after phone update. When it gets an error after the first operation it rolls back all operations.

Example scenarios:

  • Without any error:

Before:

PersonPhone => PhoneNumber: 697–555–0141

Person => ModifiedDate: 2021–01–01 00:12

After running transactional code block:

PersonPhone => PhoneNumber: 697–555–0145

Person => ModifiedDate: 2021–04–23 05:13

  • After getting an error while transactional code block running

Uncomment this line: //throw new TransactionAbortedException(“error”);

Before:

PersonPhone => PhoneNumber: 697–555–0141

Person => ModifiedDate: 2021–01–01 00:12

After running transactional code block:

PersonPhone => PhoneNumber: 697–555–0141

Person => ModifiedDate: 2021–01–01 00:12

There is no change. You can read more from the links below.

TransactionalScope class document is here.

Implementing an Implicit Transaction using Transaction Scope document is here.

--

--