how to map composite key in CRUD functionality

|▌冷眼眸甩不掉的悲伤 提交于 2020-05-28 18:53:16

问题


I need to map based on two keys(comp and 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>
    }

how to use composite key in Index page and also in controller.

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

If anyone have idea please reply.


回答1:


The find method, finds entities by the primary key. If you have a composite primary key, then pass the key values in the order they are defined in model:

@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 })

In the controller, receive both values:

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



回答2:


On applying the above suggestion, I got the error :

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.

But as per this suggestion I tried changing Details action signature to

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

CRUD functionality with composite keys executes normally now.

Thanks @Jelle Oosterbosch



来源:https://stackoverflow.com/questions/32138022/how-to-map-composite-key-in-crud-functionality

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!