我在 mvc 应用程序中有实体模型。我有两张桌子:
引擎:ID、名称、零件
部件:Id、EngineId、名称、价格
这两个表之间存在一对多的关系。
在视图中:
@model Engine
<input type="hidden" name="Id" value="@Model.Id" />
<input type="text" name="Name" value="@Model.Name" />
@for(var part in Model.Parts)
{
<input type="hidden" name="Parts.Index" value="@guide" />
<input type="hidden" name="Parts[@guide].Id" value="@part.Id" />
<input type="text" name="Parts[@guide].Name" value="@part.Name" />
<input type="text" name="Parts[@guide].Price" value="@part.Price" />
}
在控制器中:
public ActionResult Edit(int id)
{
var model = context.Engines.FirstOrDefault(x=>x.Id == id);
return View("Engine", model);
}
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var model = context.Engines.FirstOrDefault(x=>x.Id == id);
UpdateModel(model);
context.SaveChanges();
}
我正在动态添加和删除零件。当我发布时,我在 model.Parts 中有零件列表。它们都添加了实体状态。我希望所有具有 Id 的部件都具有 EntityState.Modified 并且那些被删除的部件必须具有 EntityState.Deleted 并且添加的对象应该具有 EntityState.Added。可能吗?(EF 4.0 版)