tags:

views:

165

answers:

2

Since the NHibernate ISession tracks changes, I am wondering if I can discard all changes in a session, like this:

class Person
{
    public virtual string Name { get; set; }
}

// Somewhere else...
var session = sessionFactory.OpenSession();
person.Name = "John Doe";
using(var tx = session.BeginTransaction)
{
    session.Save(person);
    tx.Commit();
}

person.Name = "Jane Doe";
// Now, can I do something like this?
session.RevertAll();
Assert.AreEqual("John Doe", person.Name);
+1  A: 
session.Clear()

With session.Clear, the NHibernate session will not contain any dirty objects anymore. But, this does not mean that your assertion will work. NHibernate will not revert the state of your object itself. In order to achieve this, you'll have to implement undoable-support yourself I guess. (You could take a look at the IEditableObject interface for this).

But, once you've saved and committed / flushed, then the changes have been made into your DB. session.Clear will not revert those changes offcourse.

Frederik Gheysels
Oh wait, then it simply removes the objects from the session, is that it?
Martinho Fernandes
+2  A: 

NH does not revert the changes you did in your entities. It is the responsibility of the business logic to care about the state of the entities.

The safest way to "undo" the changes is: rollback the transaction, clear (or recreate) the session and start from scratch.

There is a Reload method in the session. It reloads the state in the database back to the entity. But this does not work for this case, because NH could already have flushed some changes, eg. before performing a query. (It works well for detached entities.)

Stefan Steinegger