tags:

views:

11

answers:

1

In my asp.net application, I open and close/flush the session at the beginning/ending of each request.

With this setup, I thought it would result in things like:

Entity e = EntityDao.GetById(1);

e.Property1 = "blah";

EntityDao.MakePersistant(e);

e = EntityDao.GetById(1);

e.Property1 // this won't be blah, it will be the old value since the request hasn't flushed

But I noticed that the value returned was the most recent updated value. Someone responded that because of they way I have my identity setup?

Can someone explain this behaviour? So I don't need to call flush to ensure it is persisted to the db?

A: 

I belive (but could be mistaken) that nHibernate's caching and change-tracking is the reasons for this.

Since this Session instance is still active, nHibernate is tracking the changes you made to 'e'. When you ask for it again it includes those changes in the object returned. What happened when you called MakePersistant (which I assume calls Session.SaveOrUpdate(e)) is that it told that Session instance you are going to save those changes, thus it knows about them and will still show them when you call Session.Get(id) again.

If you instead started another Session and then called Session.Get(id) you wouldn't see those changes if you had not called Flush (or closed the Transaction, since you should be using a Transaction here) as it knows nothing of the changes made in the other Session.

To answer your other question, yes you still need to call Flush or close a Transaction to ensure changes are written to the database. One thing that is neat, is that you don't actually need to call SaveOrUpdate(e). For example this code will cause an Update to the database:

        using (var session = SessionFactory.OpenSession()) 
        using (var trans = session.BeginTransaction()){
            var e = session.Get(id);
            e.Name = "New Name";
            trans.Commit();
        }

nHibernate knows to update 'e' since it was tracking the changes that were made to during that Session. When I commit that transaction they are written. Note, this is the default behavior and I believe it can be changed if you want to require that .SaveOrUpdate() is called.

Chris Nicola
actually looking at sql profiler I see the db calls are made during the session, so it is hitting the db right away and not from the cache.
mrblah
What does your MakePersistent() function look like? It may be calling Session.Flush then.
Chris Nicola