【发布时间】:2010-07-13 09:13:35
【问题描述】:
我开始用 nhibernate 和 asp mvc2 开发一个 web 应用程序(应用程序组合)。
我在正确更改应用程序的类别时遇到了一些困难。
这是我的模型:
public class Application
{
public virtual int Application_ID{ get; private set; }
public virtual string Name { get; set; }
public virtual Category Category { get; set; }
}
public class Category : ILookupItem
{
public virtual int Category_ID { get; set; }
public virtual string Name { get; set; }
}
我的视图模型:
public class ApplicationEditModel
{
public Application Application { get; set; }
public SelectList Categories { get; set; }
}
我的表格:
<% Html.BeginForm(new {id= Model.Application.Application_ID }); %>
<table>
<tr>
<td><%=Html.LabelFor(x => x.Application.Application_ID)%></td>
<td><%=Html.DisplayFor(x=>x.Application.Application_ID) %></td>
</tr>
<tr>
<td><%=Html.LabelFor(x=>x.Application.Name) %></td>
<td><%=Html.EditorFor(x=>x.Application.Name) %></td>
</tr>
<tr>
<td><%=Html.LabelFor(x=>x.Application.Category) %></td>
<td><%=Html.DropDownListFor(x=>x.Application.Category.Category_ID,Model.Categories,"Select a category") %></td>
</tr>
<tr><td><input type="submit" /></td></tr>
</table>
<% Html.EndForm(); %>
我的控制器操作:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Application app = _service.FindById(id);
TryUpdateModel<Application>(app, "Application");
_service.CommitChanges();
return RedirectToAction("Index");
}
我可以分配一个新类别,但如果我更改为不同的类别,我会收到以下消息:
Core.Model.Category 实例的标识符从 2 更改为 3
这似乎是因为 defaultmodelbinder 正在更新分配类别的键,而不是使用新的新键分配新类别。
使用所有引用更新实体的正确方法是什么?
我也许可以使用自定义视图模型,将其绑定到控制器中,然后将其映射到我的域模型。但我担心它会给我太多的工作(最后我的应用程序模型中将有大约 100 个属性、30 个引用和 5-6 个列表)。
在这种情况下,Automapper 是否可以用来更新现有的域模型?
您如何处理此类更新?
【问题讨论】:
-
你找到解决这个问题的方法了吗?我现在正在遇到一模一样的问题。我正在使用 MVC3
标签: nhibernate asp.net-mvc-2 updatemodel