使用外键table列显示数据asp.net core mvc c#

Use foreign key table columns to display data asp.net core mvc c#

我有一张发票 Class,其中包含指向 FoodItem 和用户 table 的 FoodId 和 UserId 外键。

我通过将脚手架项目添加到控制器文件夹,获得了以下剃须刀页面 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 tables 中的 foodname 和 username 列。 我怎样才能做到这一点?

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

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

然后在你看来这样写;

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