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?
As others have said, your use of the Disposable pattern for this purpose is what is causing you the problems. If the pattern is working against you, then I would change the pattern. By making a commit the default behaviour of the using block, you are assuming that every use of a database results in a commit, which clearly is not the case – especially if an error occurs. An explicit commit, possibly combined with a try/catch block would work better.
However, if you really want to keep your use of the pattern as is, you can use:
in your Displose implementation to determine if an exception has been thrown (more details here).