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:
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:
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();
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:
1private readonly int _lockVersion = 0;
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)