我开始用 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 在这种情况下对更新现有的域模型有用吗?
你如何处理这种更新?