Search code examples
wpfnhibernatesession-state

nHibernate: Reset an object's original state


I have a very basic query. I am using WPF Binding to edit a object which is loaded by a ISession. If somebody edits this object in the form, because of two way binding and a stateful session, whenever I close the session, changes to the object made in the form are stored back in the database. Which is the best way to avoid this?

The methods I know:

  1. Shadow copy the object and use the copied object as the DataContext (the method I am using as of now).
  2. ISession.Clear
  3. Use IStatelessSession.

Is there any way to reset the object to it's original form before closing the ISession?


Solution

  • If you look here: http://nhforge.org/wikis/howtonh/finding-dirty-properties-in-nhibernate.aspx

    It is an example of finding dirty properties. NHibernate internally tracks a persistent object's state by way of the EntityEntry object.

    This is useful for you, because with a little modification to the method above, you're able to get old values back ... which you can use to reset the properties.

    As for closing your session causing the object to be flushed to the database, you can set the session FlushMode to FlushMode.Never. This will mean no database sync occurs until you call Session.Flush().

    Alternatively, you can hook into IFlushEntityEventListener to reset the object state. There are a reasonable examples of using the NHibernate event system on google.