【问题标题】:how to map composite key in CRUD functionality如何在 CRUD 功能中映射复合键
【发布时间】:2015-08-21 10:25:23
【问题描述】:

我需要基于两个键(comp 和 part)进行映射。

@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.comp)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.part)
            </td>
             ...........................
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.comp  }) |   
                @Html.ActionLink("Details", "Details", new { id = item.comp  }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.comp  })
            </td>
        </tr>
    }

如何在索引页面和控制器中使用复合键。

public ActionResult Edit(int? id)
    {
         DataView record = db.RecordDataView.Find(id);
            if (record == null)
            {
                return HttpNotFound();
            }
            return View(record);
        }

如果有人知道请回复。

【问题讨论】:

    标签: asp.net-mvc-5 entity-framework-5 composite-key


    【解决方案1】:

    find 方法,通过主键查找实体。如果您有复合主键,则按照它们在模型中定义的顺序传递键值:

    @Html.ActionLink("Edit", "Edit", new { comp = item.comp, part = item.part }) |   
    @Html.ActionLink("Details", "Details", new { comp = item.comp, part = item.part }) |
    @Html.ActionLink("Delete", "Delete", new { comp = item.comp, part = item.part })
    

    在控制器中,接收两个值:

    public ActionResult Edit(int? comp, int? part)
    {
        DataView record = db.RecordDataView.Find(comp, part);
        if (record == null)
        {
            return HttpNotFound();
        }
        return View(record);
    }
    

    【讨论】:

    • 非常感谢! 4 年后仍在帮助人们
    【解决方案2】:

    在应用上述建议时,我得到了错误:

    The parameters dictionary contains a null entry for parameter 'isdel' of non-nullable type 'System.Boolean' for method 'System.Web.Mvc.ActionResult Edit(System.Nullable`1[System.Int32], Boolean)' in Controller'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
    

    但是根据this suggestion 我尝试将详细信息操作签名更改为

    public ActionResult Details(int eid,bool isdeleted) //same parameter name as in my Entity Model.
    

    复合键的 CRUD 功能现在可以正常执行。

    感谢@Jelle Oosterbosch

    【讨论】:

      猜你喜欢
      • 2022-09-24
      • 2011-03-31
      • 2017-08-19
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2021-12-12
      • 2021-10-10
      • 2017-02-21
      相关资源
      最近更新 更多