【问题标题】:Binding to complex object list绑定到复杂对象列表
【发布时间】:2012-09-18 07:31:34
【问题描述】:

我在 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 版)

【问题讨论】:

    标签: asp.net-mvc-3 entity-framework-4 model-binding


    【解决方案1】:

    默认绑定器对 EF 状态一无所知。您可以为 Engine 类创建新的模型绑定器并在那里手动设置状态。

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多