Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force NHibernate to get entity that is already in persisted state / 1st level cache

Tags:

nhibernate

I have a service object that is responsible for some business logic validation. What it does, before issing Update to repository, is checking whether entity that it works on complies to some business rules.

One of that rules that is must check is if Status property of the entity didn't change when compared to entity that is in database. Because I use repositories that share the same ISession, when I try to get entity from database, in order to get an object for comparsion:

if (fromDbEntity.Status != entity.Status) throw new Exception("Cannot change status...");

I'll always get fromDbEntity that is in 1st level cache - so I work on the same object.

Is there a way to force NHibernate/Repository to get entity from database even though it's already in the scope of the session?

like image 725
dragonfly Avatar asked Dec 20 '22 20:12

dragonfly


1 Answers

Evict entity from session before loading fromDbEntity

session.Evict(entity);

You can check the official documentation for more details: Managing the caches

The con about this is that you will need to manually call SaveOrUpdate for entity since now the object is out of the session.

like image 56
Claudio Redi Avatar answered May 13 '23 15:05

Claudio Redi