tags:

views:

152

answers:

3

I'm learning Nhibernate, and there are something I'm not quite sure. I hope you can help me to check my code. As you see the following code which I did not call "SAVE" and it still updates the value to the database. There might be a situation which I want to change the objects' value and do not want to save them back to the database. How should I do this?

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UpdateShoppingCart(FormCollection collection)
    {

        int customerID = int.Parse(collection["CustomerID"]);


        foreach (var item in _shoppingCartItemReopository.GetByCustomerID(customerID))
        {

            item.DateUpdated = DateTime.Now;

            // update item one by one
            //_shoppingCartItemReopository.Save(item);
        }

        return RedirectToAction("GetUserShoppingCart", new { id = customerID });
    }

In my Gloabal.asax.cs file:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        ManagedWebSessionContext.Bind(HttpContext.Current, SessionManager.SessionFactory.OpenSession());
    }



    protected void Application_EndRequest(object sender, EventArgs e)
    {
        ISession session = ManagedWebSessionContext.Unbind(HttpContext.Current, SessionManager.SessionFactory);
        if (session != null)
        {
            try
            {
                if (session.Transaction != null && session.Transaction.IsActive)
                {
                    session.Transaction.Rollback();
                }
                else
                {
                    session.Flush();
                }
            }
            finally
            {

                session.Close();
            }
        }
    }

I hope you could check my code and provide some suggestions about open and close an session in the Application_BeginRequest and Application_EndRequest. Will doing this expensive?

Many thanks.

Daoming

A: 

Session.Flush persists all changes to the database, since you are loading an entity from your database and making changes to it those will end up in your database. If you don't want that, don't flush.

You can also change that behaviour by overriding the dirty checking but I don't think you'll want that in this case.

If you to make changes to an entity and don't want those to go into your database you'll need to rethink your session management.

BennyM
+1  A: 

That's default NHibernate behaviour. It automatically tracks changes, and when you flush your session, it will issue the necessary sql statements in order to update the records in the DB.

You can solve this in 2 ways:

  • evict the entities that you do not want to update from the Session

or

  • disable the automatic dirty tracking. This is explained here.
Frederik Gheysels
+1  A: 

Always use transactions, and use FlushMode.Commit

session.FlushMode = FlushMode.Commit
David Kemp