Mindscape LightSpeed - User Reference & API Documentation
Transactions

Transactions

There are multiple ways to use transactions with LightSpeed. The preferred way is by using the TransactionScope class. To do this simply surround any calls to LightSpeed’s Repository class with the standard TransactionScope block:

CopyUsing TransactionScope
 1using (TransactionScope transactionScope = new TransactionScope())
 2{
 3  Contribution contribution = Repository.FindOne<Contribution>(1);
 4
 5  contribution.Description = "A description";
 6
 7  Repository.CompleteUnitOfWork();
 8
 9  transactionScope.Complete();
10}

Not all ADO.NET data providers support TransactionScope however (Oracle & Postgres in particular). For these cases, the LightSpeed Repository exposes a Repository.BeginTransaction method. This method returns a standard ADO.NET System.Data.IDbTransaction object. In this case, the usage pattern is slightly different as we need to flush changes using the Repository.SaveChanges method before committing the transaction and then completing the unit of work:

CopyUsing Standard .NET Transactions
 1using (IDbTransaction transaction = Repository.BeginTransaction())
 2{
 3  Contribution contribution = Repository.FindOne<Contribution>(1);
 4
 5  contribution.Description = "A description";
 6
 7  Repository.SaveChanges();
 8
 9  transaction.Commit();
10}
11
12Repository.CompleteUnitOfWork();

LightSpeed ensures that all database flush operations run within a transaction.
 

Optimistic Concurrency Control

Optimistic concurrency control is an efficient method of maintaining data integrity without using database level locks. It is ideal for web applications and applications where there is usually a low likelyhood of conflicting transactions. LightSpeed implements optimistic locking using row versioning. Under this schema each row has a version number and this version number is used to validate whether updates or delete operations may proceed. If a conflict is detected LightSpeed will throw an OptimisticConcurrencyException.

To use LightSpeed optimistic locking simply add a field (and a corresponding column to the target table) called lockVersion:

CopyEnabling optimistic locking
1private readonly int _lockVersion = 0;

CopyCreating the Contribution table
1CREATE TABLE Contribution
2(
3  Id            INT          NOT NULL PRIMARY KEY,
4  ContributorId INT          NOT NULL FOREIGN KEY REFERENCES Member(Id),
5  Title         NVARCHAR(50) NOT NULL,
6  LockVersion   INT          NOT NULL DEFAULT 0
7)

The name of the lock version column can be customized using INamingStrategy.