Search code examples
asp.net-mvc-5entity-framework-5composite-key

how to map composite key in CRUD functionality


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.


Solution

  • 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);
    }