gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:22:16 26 4
gpt4 key购买 nike

我正在学习 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 });
}

在我的 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();
}
}
}

我希望您能检查我的代码并提供一些有关在 Application_BeginRequest 和 Application_EndRequest 中打开和关闭 session 的建议。这样做会很贵吗?

非常感谢。

道明

最佳答案

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

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

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

  • 禁用自动脏跟踪。这是解释here .

关于c# - NHibernate 自动将我的对象更新到数据库,而无需在 Asp.Net MVC 中调用 SaveOrUpdate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2199221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com