views:

73

answers:

2

I have a piece of code i recently expanded but now must use a transaction. It looks like it can only be access while in a transaction but looks like doesnt make me feel comfortable. Using SQLite and ADO.NET i wrote if(cmd.Transaction==null) but it is null and in a transaction. How should i check?

NOTE: I will be using this code with TSQL in the future. This is a quick prototype with SQLite

-edit- i was thinking of nesting transactions but this code generates a piece of sql and uses a command to add parameters too. So adding a nested transaction would take a lot of modification.

+1  A: 

Depending on the nature of the SQL and its fit in the application, it may be more appropriate for you to nest transactions, ensuring a transaction is present regardless of the context of the call.

For example, you could wrap the calling code in a TransactionScope block. If there is a transaction present, this will have no real effect on the operation. If there is no transaction present, it will create a transaction and ensure the ADO.NET code participates in the transaction.

This approach only works if you're happy for the SQL to be executed as a single operation. If it should only be called as part of a larger transaction, this approach doesn't help.

To know for sure that a transaction is present, you have to check for the explicit transaction on the ADO.NET command (as you have above) and also the presence of an ambient transaction from the System.Transactions programming model using the Transaction.Current property.

Programming Hero
I dont see a Transaction.Current but i can write `cmd.Transaction = tns;`
acidzombie24
The Transaction class is in System.Transactions namespace, which is found in the System.Transactions assembly.
Programming Hero
A: 

In SQLite.NET library there is a method under connection class called BeginTransaction. You can use that method to keep track of transactions.

SQLiteConnection cn = new SQLiteConnection(connectionStringHere);
SQLiteTransaction transaction;
transaction = cn.BeginTransaction();
Aseem Gautam