문제

Maybe this is a really noob question since I'm fairly new to handling transactions with PetaPoco. Problem I'm facing using PetaPoco as a microORM to handle my db transaction is that if I throw an exception just before the .Complete() method of the transaction, everything is rolled back correctly but if I'm catching exceptions inside the

Using scope As PetaPoco.Transaction = db.GetTransaction()
    ' try/catch here and if the db command fails transaction won't roll back

    scope.Complete()
End Using

the transaction won't roll back if one of the db operations fails. How can I solve this?

도움이 되었습니까?

해결책

The issue was me not handling correctly the "call/not call" the scope.Complete() based on Exceptions intercepted along the path. In particulart I had a boolean flag "rollBackTransaction" starting to false and then updating to true if any of the try/catch block inside the transaction raised and exception. At the end I just checked it:

                    If Not rollBackTransaction Then
                        scope.Complete()
                    End If

This can be used as well for the TransactionScope suggested by Simon wich will eventually roll back a transaction if .Complete() is not called before closing the Using block.

Now what was causing a false flag and thus calling the scope.Complete() method each time, was that inside the transaction I called a sub wich had it's own exception handling and thus would never raise an exception in the main transaction block to correctly update the "rollBackTransaction" flag.

What I learned is that if you are using try/catch inside the transaction, be very sure that the external methods you call raise an exception if they fall, and update a flag all along based on wich you will call the scope.Complete().

Anyway Simon, thanks for pointing out that .NET feature I didn't know wich seems to be extremely useful! Wonder what else it will include in the transaction... file system changes?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top