You can lock a row in the database by starting a transaction for its respective object. You can use the FlushChanges
methods to do this.
The FlushChanges method can be used to flush changes made to an object without committing the initiated transaction. This will cause the row for the respective object to be locked. In such scenario, trying to access the locked object concurrently will cause LockNotGrantedException
and trying to update a locked object will cause OptimisticVerificationException
. To unlock the locked rows you must commit the transaction using the SaveChanges
or roll it back with ClearChanges
Note that to use FlushChanges
the object which you wish to lock has to have some changes in it. To avoid pushing fake data to the database in order to lock the object, you can use the MakeDirty
method to mark a property of the object as dirty without actually changing its value. This needs to be done prior
to calling the FlushChanges method.
I have attached a sample project illustrating this approach to locking database rows. Note that to run the project you will need to SofiaCarRental
database. You would also need to update the connection string in the app.config and upgrade the OpenAccess references
In your specific scenario, you could listen for the changing or changed event and initiate a transaction with the aforementioned approach to lock the respective database row in the handler for the event. Do note that since the rows will be locked as long as the transaction is not committed, this may introduce problems if the user of the application does not complete the editing.
I hope this helps. Should you have additional questions, feel free to post at our forums again.
OpenAccess ORM is now Telerik Data Access
. For more information on the new names, please, check out the Telerik Product Map