Pattern for handling an ADO.net transaction
-
I've been using the following pattern with transactions for some time now, without problems.
try
{
// begin transaction
// do stuff
// Commit
}
catch ( System.Exception err )
{
// log err
// Rollback
}I have been operating under the assumption that if Commit or Rollback is called for a non-existent transaction, then throwing an exception is the right thing to do. The Commit and Rollback in question are my methods that check for null and throw InvalidOperationException rather than NullReferenceException. But recently I've run into some problems. For some reason (which I still need to investigate further, but I have an idea) the Commit fails because the transaction doesn't exist, which means the Rollback will also fail. Having an exception thrown through the catch is, of course, nasty. I could change the methods to raise an event instead of throwing. I could filter the exception to log but not rollback on certain exceptions (like InvalidOperationException). Has anyone else had to deal with this situation? Does anyone have a better pattern for this?
-
I've been using the following pattern with transactions for some time now, without problems.
try
{
// begin transaction
// do stuff
// Commit
}
catch ( System.Exception err )
{
// log err
// Rollback
}I have been operating under the assumption that if Commit or Rollback is called for a non-existent transaction, then throwing an exception is the right thing to do. The Commit and Rollback in question are my methods that check for null and throw InvalidOperationException rather than NullReferenceException. But recently I've run into some problems. For some reason (which I still need to investigate further, but I have an idea) the Commit fails because the transaction doesn't exist, which means the Rollback will also fail. Having an exception thrown through the catch is, of course, nasty. I could change the methods to raise an event instead of throwing. I could filter the exception to log but not rollback on certain exceptions (like InvalidOperationException). Has anyone else had to deal with this situation? Does anyone have a better pattern for this?
Well, the transaction can easily be checked by looking at the transaction on your command, e.g
if (myCommand.Transaction != null)
{
myCommand.Transaction.Commit();
}Deja View - the feeling that you've seen this post before.
-
Well, the transaction can easily be checked by looking at the transaction on your command, e.g
if (myCommand.Transaction != null)
{
myCommand.Transaction.Commit();
}Deja View - the feeling that you've seen this post before.
Yes, and I do, but if it is null, I throw InvalidOperationException, because I feel that the caller should know about it. I don't want to continue as if everything was okey-dokey. I check the same thing in my Rollback method as well, which is causing the trouble.