I have a scenario where it requires to add a record in to table, then - creating a resource on the cloud if record is added, then update the record in table with the resource identifier if resource is created on cloud. So, they are 3 operations and I want to revert all of it when any of them doesn't succeed.
We have TransactionScope for Multiple Db Operations in one go but I'm wondering how to achieve this? Appreciate your help!
Edit
PS: There could be any number of operations like that - say 10 or more in a sequence, and they may not even related to DB operations. They could just be creating 10 files in a sequence - so when any of the file creation fails - all the previous files should be deleted/undone.
How about going a command pattern way? It's may not be perfect command pattern implementation but something very close. See below:
Similarly you would create commands for creating cloud resource and updating record in db. In main code you can hold collection of ICommand objects and execute each one.
Then in the loop you can call
Execute
, if it returnsSuccess = false
then record the current command index in collection and loop backward whilst callingRollback
on each command.I assume you are using Azure as cloud. So to support transactions you need to have -
1. Elastic database on Azure which supports transactions.
2. You need to have .NET framework 4.6.1 or higher to utilize distributed transaction.
I encourage you to go through https://docs.microsoft.com/en-us/azure/sql-database/sql-database-elastic-transactions-overview
Now in your case lets break 3 steps considering transaction scope is applied.
If this fails then no worries I guess.
If this fails then Added record will be rolled back.
If this fails then 1 step will be rolled back.
After transaction scope is finished you need to check that record added in 3rd step exists. If it does not then you need to manually rollback resource creation by deleting it.