问题
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?
回答1:
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.
回答2:
You could, as Claudio suggests, evict the entity
from the session, then load your fromDbEntity
, do the comparison and then Merge the entity again with the session.
Other thing you might do is loading the fromDbEntity
using the stateless session instead.
But is this really necessary? Couldn't you just make your Status
property read-only? NHibernate is perfectly capable of using fields for accessing data. Or you could make your property setter protected
:
public virtual Status Status { get; protected set; }
This way the user won't be able to change the property value, so there's no need to check whether current value is different from db one.
回答3:
I had a similar issue, I solved it by clearing the session before any call that I want to go all the way to the data base.
session.Clear();
It's a little overkill but it works.
回答4:
The way you sate your logic, it sounds like there's a potential bug. A much better solution would be to turn on dynamic-update, thus only updating changed values, then validate that no one has changed Status before saving.
来源:https://stackoverflow.com/questions/11016356/force-nhibernate-to-get-entity-that-is-already-in-persisted-state-1st-level-ca