使用外键表列显示核心 mvc c# asp.net 数据



我有一个发票类,其中包含 FoodId 和 UserId 外键到 FoodItem 和 User 表。

我有以下剃须刀片页面 Index.cshtml 将脚手架项目添加到控制器文件夹。

@model IEnumerable<WebApplication1.Models.Invoice>
@{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link rel="stylesheet" href="~/css/SideBar.css" />
<div class="sidebar">
<a asp-controller="Admin">Main Page</a>
<a asp-controller="FoodItems">Food List</a>
<a class="active" asp-controller="Invoices">Invoice</a>
<a asp-controller="Role">Users & Roles</a></div>
<h1>Invoice</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserId)
</th>
<th>
@Html.DisplayNameFor(model => model.FoodId)
</th>
<th>
@Html.DisplayNameFor(model => model.totalsum)
</th>
<th>
@Html.DisplayNameFor(model => model.quantity)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
@Html.DisplayFor(modelItem => item.FoodId)
</td>
<td>
@Html.DisplayFor(modelItem => item.totalsum)
</td>
<td>
@Html.DisplayFor(modelItem => item.quantity)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.InvoiceId">Edit</a> |
<a asp-action="Details" asp-route-id="@item.InvoiceId">Details</a> |
<a asp-action="Delete" asp-route-id="@item.InvoiceId">Delete</a>
</td>
</tr>
}
</tbody>
</table>

我想列出而不是 FoodId 和 UserId ,从 FoodItem 和 UserId 表中引入列食物名称和用户名。 我怎样才能做到这一点?

当您检索发票实体包括食物和用户时,如下所示:

_context.Invoices.Include(x => x.Users).Include(x => x.Food).ToList();

然后在你看来这样写;

@Html.DisplayNameFor(model => model.User.Name)
@Html.DisplayNameFor(model => model.Food.Name)

最新更新