我在 ASP.Net MVC4 中使用 nhibernate 更新对象时遇到问题 我在这种情况下进行更新:
the application loads an object in the first session
the object is passed up to the UI tier
some modifications are made to the object
the object is passed back down to the business logic tier
the application persists these modifications by calling SaveOrUpdate()
所有这一切只发生在一个会话中。我有一个静态的类名 NHibernateSessionPerRequest 并且它的构造函数是静态的(单例)
[HttpPost]
public ActionResult Edit(Menu menu)
{
if (ModelState.IsValid)
{
repository.SaveOrUpdate(menu);
TempData["message"] = string.Format("{0} has been saved", menu.Name);
return RedirectToAction("Index");
}
else
{
// there is something wrong with the data values
return View(menu);
}
}
但菜单 ID 为零。并且没有其原始 ID(id 是 GUID 的类型)。并且 SaveOrUpdate() 总是将其视为一个新对象并保存它而不是更新它。
这是Edit.cshtml:
@model MyApp.Domain.Entities.MenuComponent
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_AdminLayout.cshtml";
}
<h2>Edit @Model.Name
</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>MenuComponent</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Description)
@Html.ValidationMessageFor(model => model.Description)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
如何更新对象?