结论每页子记录

时间:2016-09-18 07:55:48

标签: asp.net asp.net-core

我有一个名为Invoice的表,它在寄售单中有一个子表项。还有一张商品表。

在MVC 5中,可以在页面上进行以下构造:

@foreach (var item in Model)
{
<tr>
    <td>
    @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @foreach (var items in item.ListProdukts)
        {

            @Html.DisplayFor(modelItem => items.Produkts.ProduktName)
        }

但这在ASP.NET Core中不起作用。

型号:

namespace Proba3.Models
{
    public class Invoice
{
    public int InvoiceId { get; set; }
    public string InvoiceName { get; set; }
    public ICollection<ListProdukt> ListProdukts { get; set; }

}
}

namespace Proba3.Models
{
    public class ListProdukt
    {
        public int ListProduktId { get; set; }
        public int ProduktId { get; set; }
        public virtual Produkt Produkts { get; set; }

        public int InvoiceId { get; set; }
        public virtual Invoice Invoices { get; set; }
    }
}

 namespace Proba3.Models
 {
     public class Produkt
     {
        public int ProduktId { get; set; }
        public string ProduktName { get; set; }
        public ICollection<ListProdukt> ListProdukts { get; set; }
    }
}

控制器:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Proba3.Data;
using Proba3.Models;

namespace Proba3.Controllers
{
public class InvoicesController : Controller
{


    private readonly ApplicationDbContext _context;

    public InvoicesController(ApplicationDbContext context)
    {
        _context = context;    
    }

    // GET: Invoices
    public async Task<IActionResult> Index()
    {
       var applicationDbContext = _context.Invoice.Include(c => c.ListProdukts);

        return View(await applicationDbContext.ToListAsync());
    }

查看:

@model IEnumerable<Proba3.Models.Invoice>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.InvoiceName)
        </th>
        <th></th>
    </tr>
</thead>
<tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.InvoiceName)
            </td>
            <td>
            @foreach (var items in item.ListProdukts)
            {
                <p>@Html.DisplayFor(modelItem => items.ProduktId)</p>
                <p>@Html.DisplayFor(modelItem => items.Produkts.ProduktName)</p>
            }
            </td>
            <td>

为什么不显示ProduktName?

1 个答案:

答案 0 :(得分:0)

答案在github上给出。

事实证明,ASP.NET Core现在默认不添加子元素。 可在此处阅读详细信息:docs.asp.net

在我的情况下,有必要添加到Controller:

连续:

var applicationDbContext = _context.Invoice.Include (c => c.ListProdukts) .ThenInclude (c => c.Produkts);

这样:

.ThenInclude (C => c.Produkts);