3
votes

I was surprised to find no documentation on the subject, does anyone know if OrmLite supports Optimistic Concurrency? Any documentation or example references would be most welcome.

1
As far as I know Ormlite provide wrapper around IDBConnection, very thin wrapper. And if you are using 'using' it will close connection for you. Nothing specifically is getting done for Concurrency. Transaction is also there as part of IDBConnection. - kunjee

1 Answers

1
votes

That's not really up to OrmLite. It depends on the isolation level and your database setup.

Example:

using (var trans = Db.BeginTransaction(IsolationLevel.ReadCommitted) as SqlTransaction)
            {
                try
                {
                    //do something
                    trans.Commit();
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    throw ex;
                }
            }
}

From MS SQL Sever Docs

READ COMMITTED
Specifies that statements cannot read data that has been modified but not committed by other transactions. This prevents dirty reads. Data can be changed by other transactions between individual statements within the current transaction, resulting in nonrepeatable reads or phantom data. This option is the SQL Server default. The behavior of READ COMMITTED depends on the setting of the READ_COMMITTED_SNAPSHOT database option:

If READ_COMMITTED_SNAPSHOT is set to ON, the Database Engine uses row versioning to present each statement with a transactionally consistent snapshot of the data as it existed at the start of the statement. Locks are not used to protect the data from updates by other transactions.

Alternatively, you can use BeginTransaction(IsolationLevel.Snapshot) and have optimistic concurrency in that you avoid locks, but SQL Server uses rowversion before committing to avoid modifying data that was modified outside the current transaction.

From other MS SQL Server docs:

Transactions running under snapshot isolation take an optimistic approach to data modification by acquiring locks on data before performing the modification only to enforce constraints. Otherwise, locks are not acquired on data until the data is to be modified. When a data row meets the update criteria, the snapshot transaction verifies that the data row has not been modified by a concurrent transaction that committed after the snapshot transaction began. If the data row has been modified outside of the snapshot transaction, an update conflict occurs and the snapshot transaction is terminated. The update conflict is handled by the Database Engine and there is no way to disable the update conflict detection.