Asp.net-Mvc-5

如何在 CRUD 功能中映射複合鍵

  • May 24, 2020

我需要基於兩個鍵(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);
       }

如果有人有想法請回复。

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

引用自:https://stackoverflow.com/questions/32138022