I have the following code in my application:
using (var database = new Database()) {
var poll = // Some database query code.
foreach (Question question in poll.Questions) {
foreach (Answer answer in question.Answers) {
database.Remove(answer);
}
// This is a sample line that simulate an error.
throw new Exception("deu pau");
database.Remove(question);
}
database.Remove(poll);
}
This code triggers the Database class Dispose() method as usual, and this method automatically commits the transaction to the database, but this leaves my database in an inconsistent state as the answers are erased but the question and the poll are not.
There is any way that I can detect in the Dispose() method that it being called because of an exception instead of regular end of the closing block, so I can automate the rollback?
I don´t want to manually add a try ... catch block, my objective is to use the using block as a logical safe transaction manager, so it commits to the database if the execution was clean or rollbacks if any exception occured.
Do you have some thoughts on that?