There's more…
Session.Lock
is not the only way these lock modes can be used. We can also use overloads on session.Load
or session.Get
.
var product = session.Load<Product>(1, LockMode.Upgrade);
Note that LockMode.Upgrade
or LockMode.UpgradeNoWait
changes the behavior of session.Load
. Normally it will not call the database, until the loaded entity is being used. When a lock is required, the database must be involved and the entity will be loaded immediately.
We can also specify the lock mode on a query, effectively acquiring locks on all the entities it returns. For an HQL query it looks similar to this:
session.CreateQuery("from Movie m where m.Director = :director") .SetString("director", directorName) .SetLockMode("m",LockMode.Upgrade) .List<Movie>(); ...
Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.