In most cases locking is something that you want to avoid as it limits the level of concurrency of your database. But sometimes that is exactly what you want.
You can use pessimistic concurrency in NHibernate by using an overload that takes a LockMode:
When using session.Get<T>:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var session = sessionFactory.OpenSession()) | |
using (var tx = session.BeginTransaction()) | |
{ | |
var person = session.Get<Person>(1,LockMode.Upgrade); | |
person.Name = "other"; | |
tx.Commit(); | |
} |
Or when using session.Query<T>:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using (var session = sessionFactory.OpenSession()) | |
using (var tx = session.BeginTransaction()) | |
{ | |
var person = session | |
.Query<Person>() | |
.WithLock(LockMode.Upgrade) | |
.Where(p => p.Id==1) | |
.Single(); | |
person.Name = "other"; | |
tx.Commit(); | |
} |