Force NHibernate to receive an entity that is already in a state of persistence / first level cache

I have a service object that is responsible for some business logic validation. What he does, before going to the Update to Repository repository, checks if the object he is working on complies with some business rules.

One of these rules that must be checked is that the Object Status property has not changed compared to the entity in the database. Since I use repositories that use the same ISession when I try to get an entity from a database to get an object for comparison:

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

I always get fromDbEntity , which is in the 1st level cache, so I am working on the same object.

Is there a way to force NHibernate / Repository to retrieve an object from the database, even if it is already in the session scope?

+4
source share
4 answers

Get entity out of session before loading fromDbEntity

 session.Evict(entity); 

You can find out more about official documentation: Cache Management

This means that you need to manually call SaveOrUpdate for the entity , since the object has now logged out of the session.

+6
source

You can, as Claudio suggests, cut the entity out of the session, then load your fromDbEntity , perform a comparison, and then Merge the object again with the session.

Another thing you can do is load fromDbEntity using a stateless session .

But is it really necessary? Could you just make your Status resource read-only? NHibernate knows how to use fields to access data. Or you can make your property adjuster protected :

 public virtual Status Status { get; protected set; } 

Thus, the user will not be able to change the value of the property, so there is no need to check whether the current value is different from db.

+3
source

I had a similar problem, I solved it by clearing the session before any call that I want to go to the database.

 session.Clear(); 

A bit overkill, but it works.

+1
source

The way you saturate your logic sounds like a potential mistake. The best solution would be to enable dynamic updating, thus only updating the changed values, and then confirm that no one has changed the status before saving.

0
source

All Articles