How to deal with transactions in c# .net

Dheeraj Thodupunuri
1 min readAug 31, 2020

Why transactions?

Lets take an example . Suppose we have database operation where we need to insert a record into DB table and after successful insertion you need to perform some other operation like in my case i want to insert an image into azure blob.Now , if inserting into azure blob storage fails we have to delete the record from database for consistency in database. For such scenarios we can use transactions.

What are transactions?

A transaction is a set of operations where all of them must be successful or fail to ensure consistency that means the job is never half done.

Example:

In the above example in SaveCustomerAdditionalDetails method , after successful insertion to DB , there are two more operations need to done that is SaveToAzureBlob . If SaveToAzureBlob fails we need to rollback DB .

So , in order to do that i have started transaction using BeginTransaction() method of SqlConnection class . Once your operations are successful commit the transaction using Commit() method else Rollback using Rollback() method.

NOTE:-

Until transaction.commit() is executed , changes are not reflected in our database.

--

--