We help IT Professionals succeed at work.

Perform commit rollback transaction on strongly typed tableadapter.

i try to perform commit rollback transaction on strongly typed tableadapter.
using (dt1TableAdapters.Level_Subject_TopicTableAdapter adpt300 = new dt1TableAdapters.Level_Subject_TopicTableAdapter())


Open in new window

Watch Question

surround the code that you want in a transaction with

using (trans  = new TransactionScope(TransactionScopeOption.Required))
    // put your your code here

When the "Commit" method is called, your transaction will be committed, if it is not (because an exception was raised and the call to Commit was not executed, the transaction will be rolled back.

You need to add a reference to System.Transactions.


found that there's no trans.Commit but trans.Complete, Complete - Indicate that all operations within the scope are completed successfully. are they working the same.?

wait there, u mean the transactionscope will automatically rollback if any error occur within the using (TransactionScope .. )  ?
You're correct about the Complete method instead of Commit.  I was typing the example in the browser and forgot to verify if it was correct.

If then TransactionScope is disposed (at the end of the using block), it will automatically rollback the transaction if the Complete method has not been called.  That is the case if the Complete method is the last statement of the block, and an exception happens before that.

So, if the code can execute normally, the transaction is committed, if the code is interrupted before the call to Complete, the transaction is rolled back.

The only drawback is, if you open multiple connections (even if they are to the same database) in the same transaction, this mechanism will use MSDTC (distributed transaction coordinator) which is a bit slow.  The workaround, if you only use 1 database, is to keep using the same database-connection for everything in the same transaction, but that makes your code more complex, so you probably only want to do that if performance is really a problem after you start using transactions.