how to map composite key in CRUD functionality
Asked Answered
K

2

9

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.

Knut answered 21/8, 2015 at 10:25 Comment(0)
M
10

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);
}
Marge answered 21/8, 2015 at 11:25 Comment(1)
Thank you very much! still helping folks 4 years laterAllium
A
0

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

Aircraftman answered 24/5, 2020 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.