开发者

confused why are my entities changes reflected w/o committing?

开发者 https://www.devze.com 2022-12-14 15:07 出处:网络
I am using nhiberate, with the repository patter. e.g. MakePersistance looks like: public T MakePersistent(T entity)

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??


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

0

精彩评论

暂无评论...
验证码 换一张
取 消