NHibernate自动将我的对象更新到数据库,而无需在Asp.Net MVC中调用SaveOrUpdate

Dao*_*ang 2 c# nhibernate

我正在学习Nhibernate,有些东西我不太确定.我希望你能帮我检查一下我的代码.当您看到以下代码时,我没有将其称为" SAVE ",它仍然会更新数据库的值.可能存在我想要更改对象值并且不想将它们保存回数据库的情况.我该怎么做?

    [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 });
    }
Run Code Online (Sandbox Code Playgroud)

在我的Gloabal.asax.cs文件中:

    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();
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

我希望您可以检查我的代码并提供有关在Application_BeginRequest和Application_EndRequest中打开和关闭会话的一些建议.会这么贵吗?

非常感谢.

道明

Fre*_*els 5

这是默认的NHibernate行为.它会自动跟踪更改,当您刷新会话时,它将发出必要的sql语句以更新数据库中的记录.

您可以通过两种方式解决此问题:

  • 驱逐您不想从Session更新的实体

要么