Question:
Good afternoon to everyone who faced such a problem.
There is a table Invoice, it has a child table goods in the invoice. And there is a table of goods.
MVC 5 It was possible to make the following construction on the pages:
@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)
}
But in ASP.Net Core it doesn't work. While the studio gives all these fields in the code hints.
Model:
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; }
}
}
Controllers:
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());
}
Views:
@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>
Why doesn't it show ProductName?
Answer:
The answer was given on github.
It turns out ASP.NET Core no longer adds child elements by default. Details can be read in English here: docs.asp.net
In my case, in the Controller you need to add:
to the line:
var applicationDbContext = _context.Invoice.Include(c => c.ListProdukts).ThenInclude(c => c.Produkts);
this:
.ThenInclude(c => c.Produkts);