4

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?

dragonfly
  • 17,407
  • 30
  • 110
  • 219

4 Answers4

7

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.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
3

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.

Community
  • 1
  • 1
Miroslav Popovic
  • 12,100
  • 2
  • 35
  • 47
1

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.

Mr Mush
  • 1,538
  • 3
  • 25
  • 38
0

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.

JeffreyABecker
  • 2,724
  • 1
  • 25
  • 36