Hello, I started to develop a web application (application portfolio) with nhibernate and asp mvc2.
I have some difficulties to properly change the category of an application.
Here are my models:
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; }
}
My viewModel:
public class ApplicationEditModel
{
public Application Application { get; set; }
public SelectList Categories { get; set; }
}
My Form:
<% 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(); %>
My controller action:
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
Application app = _service.FindById(id);
TryUpdateModel<Application>(app, "Application");
_service.CommitChanges();
return RedirectToAction("Index");
}
I can assign a new category, but if I change to a different category I get the following message:
identifier of an instance of Core.Model.Category was altered from 2 to 3
This seems to be because the defaultmodelbinder is updating the key of the assigned category instead of assigning a new category with new new key.
What is the correct way to update an entity with all its references?
I could maybe use a custom view model, bind it in the controller, and then map it to my domain model. But I fear that it will give me too much work (at the end I will have around 100 properties,30 references and 5-6 lists in my application model).
Could Automapper be useful in this case to update an existing domain model?
How are you handling this kind of update?