tags:

views:

38

answers:

2

I am using nhiberate, with the repository patter.

e.g. MakePersistance looks like:

 public T MakePersistent(T entity)
        {
            Session.Save(entity);

            return entity;
        }

In a httpmodule the begin request:

ISession session = NHibernateHelper.OpenSession();
 session.BeginTransaction();

 CurrentSessionContext.Bind(session);

End Request:

ISession session = CurrentSessionContext.Unbind(
            NHibernateHelper.SessionFactory);

            if (session != null)
                try
                {
                    session.Transaction.Commit();
                }
                catch (Exception ex)
                {
                    session.Transaction.Rollback();
                    //Server.Transfer("...", true);
                }
                finally
                {
                    session.Close();
                }

So on each page request, the transaction starts and ends.

From what I understood, this means that if I update an entity, and then query for that entity after the update, the query would return the original state of the entity since the update hasn't been committed to the database.

But, I tested (and viewed in sql profiler) that the db performs the update and then retrieval of the same entity is fresh/up-to-date.

So I did:

Entity e = EntityDao.GetById(1);

// e.count outputs 0

e.Count += 1;

// e.count outputs 1 as expected

EntityDao.MakePersistant(entity);

entity = EntityDao.GetById(1);  // getting from the db again

// e.count ouputs 1  ***

Shouldn't it be 0 though since the db is stale until the request ends and commits to the db??

+1  A: 

If your entity's primary key is identy column this is normal behavior, as NHibernate HAS to persist the data to the database in order to get the entity's ID so it can place it in its session. This is the case with all Post Insert Generators. If do not want that to happen and also to gain many other benefits you should select to use one of the ORM Style Generators like the HiLo/Sequence HiLo generator

Have a look at this for more info:

http://nhforge.org/blogs/nhibernate/archive/2009/03/20/nhibernate-poid-generators-revealed.aspx

tolism7
A: 

No, it should be 1. You are requesting the entity from within the same session from which you performed the update. This means that the entity is not retrieved from the db, but from the 1. level cache. You won't see a second SELECT if you look in the profiler (because there is no roundrip to the db when you perform the second fetch from the repository).

Marius