Abdullah BaMusa
Abdullah BaMusa

Reputation: 1069

How to save in Transaction?

Consider this scenario; suppose I have WPF window which have four objects bonded to its controls (Schedule, Customer, Contract, ScheduleDetails and Signer specifically ) which represent four database tables in the backend database. I want when the user request save for the information he/she entered to be joined in atom operation in another words all saving operation be in one transaction so either all operations success or all failed. My question is what is the most efficient way to represent transaction operation in this scenario

Upvotes: 3

Views: 586

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063338

The most efficient is to use BeginTransaction etc on your DbConnection, but this isn't convenient, as you must use the same connection, and each DbCommand needs the transaction setting etc.

The simplest is TransactionScope, and if you are on SQL-Server 2005 or above, you will rarely notice a significant performance difference between this and BeginTransaction:

using(var tran = new TransactionScope()) {
    SaveA();
    SaveB();
    SaveC();
    SaveD();
    tran.Complete();
}

Here it doesn't matter if SaveA etc use the same connection, as SqlConnection will enlist into a TransactionScope automatically.

Alternatively, let an ORM handle this for you; most will create transactions for saving a group of changes.

One thing to watch; TransactionScope relies on services (DTC) that may not be available on all clients (since you mention WPF, which is client-side).

Upvotes: 4

Related Questions