Transactions and exception handling  
Author Message
EisenB





PostPosted: .NET Framework Data Access and Storage, Transactions and exception handling Top

Hello all,

I have one method that starts a transaction and passes it to three methods to do an updates.

private void A()

{

int intRecordsAffected;

Transaction T = GlobalConnection.BeginTransaction();

intRecordsAffected = B(T);

intRecordsAffected = intRecordsAffected + C(T);

intRecordsAffected = intRecordsAffected+ D(T);

MessageBox.Show(intRecordsAffected.ToString());

T.Commit();

}

If an exception occurs in B, C, or D how can I make A aware of it so that it can rollback

Thanks,

Eisen




.NET Development25  
 
 
EisenB





PostPosted: .NET Framework Data Access and Storage, Transactions and exception handling Top

I was able to achieve this by not using try catch in the method being called, but using try catch in calling the method.

private void A()

{

int intRecordsAffected;

Transaction T = GlobalConnection.BeginTransaction();

try

{

intRecordsAffected = B(T);

intRecordsAffected = intRecordsAffected + C(T);

intRecordsAffected = intRecordsAffected+ D(T);

T.Commit();

}

catch

{

T.Rollback();

}

MessageBox.Show(intRecordsAffected.ToString());



 
 
VMazur





PostPosted: .NET Framework Data Access and Storage, Transactions and exception handling Top

Commit should be the last line of code after database manipulation, but BEFORE (not after) catch section. Rollback should be in a catch section in this case

private void A()

{

int intRecordsAffected;

Transaction T = GlobalConnection.BeginTransaction();

try

{

intRecordsAffected = B(T);

intRecordsAffected = intRecordsAffected + C(T);

intRecordsAffected = intRecordsAffected+ D(T);

T.Commit();

}

catch

{

//rollback transaction here

}

}