Database.EnsureInTransaction Method (IsolationLevel)

Returns a virtual transaction that you can use to ensure a code block is always executed in a transaction, new or existing.

Namespace:  DbExtensions
Assembly: DbExtensions.dll

Syntax

public IDbTransaction EnsureInTransaction(
	IsolationLevel isolationLevel
)

Parameters

isolationLevel

Type: System.Data.IsolationLevel
Specifies the isolation level for the transaction. This parameter is ignored when using an existing transaction.

Return Value

Type: IDbTransaction
A virtual transaction you can use to ensure a code block is always executed in a transaction, new or existing.

Remarks

This method returns a virtual transaction that wraps an existing or new transaction. If Current is not null, this method creates a new TransactionScope and returns an IDbTransaction object that wraps it, and by calling Commit() on this object it will then call Complete() on the TransactionScope. If Current is null, this methods begins a new IDbTransaction, or uses an existing transaction created by a previous call to this method, and returns an IDbTransaction object that wraps it, and by calling Commit() on this object it will then call Commit() on the wrapped transaction if the transaction was just created, or do nothing if it was previously created.

Calls to this method can be nested, like in the following example:

void DoSomething() {

   using (var tx = this.db.EnsureInTransaction()) {

      // Execute commands

      DoSomethingElse();

      tx.Commit();
   }
}

void DoSomethingElse() { 

   using (var tx = this.db.EnsureInTransaction()) {

      // Execute commands

      tx.Commit();
   }
}

See Also

Reference

Database Class
DbExtensions Namespace

© Max Toro Q.