4

I have a call that needs to determine if a field has changed. But calling get using that entities id returns the same entity not the prior version.

Entity e = Dao.Get(id); //At this point e.Field is X e.Field = y; Dao.Save(e); Entity Dao.Get(Guid id) { return Session.Get(id); } Entity Dao.Save(Entity e) { Entity olde = Session.Get(e.Id); if (e.Field != olde.Field) <--- e.Field == olde.Field so it does not run. DoBigMethod(e); return e; } 

How do I handle this situation without adding an onChange method to the Entity class.

1 Answer 1

1

You only know one "version" of the entity: the current one. There is actually only one version of the entity. You have it in memory and you already changed it and forgot the previous state.

Call get to see the previous database state is dangerous. If changes are already flushed (NHibernate flushes before queries for instance), you get your changes. If you open another session, you see changes from other transactions.

Are you only interested in one single field? Then you can cache the old value somewhere.

If this wouldn't work, you need to tell me more about the reason why you need to know the previous value of this field.

EDIT:

Some more ideas:

  • cache the previous state of the field when you get the object, in DAO.Get
  • implement this property that it sets a flag if it changed.
  • consider to make this change an explicit operation called by the client, instead of an implicit operation that is called when the flag changes. For instance, if this flag is called "Activated", implement a "Activate" and "Deactivate" method. This methods change that flag and perform the "large set of code". The flag is read-only for the rest of the world.
Sign up to request clarification or add additional context in comments.

2 Comments

We have an flag on a user that if it changes runs a large set of code. This code will throw exceptions in certain cases. I do not need to do this check if they are just updating other fields. Exceptions would be unlikely in those cases.
I added some more ideas to my answer. Hope it helps.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.