【发布时间】:2018-03-27 13:34:02
【问题描述】:
我正在尝试使由 EF 核心创建的 DotnetCore C# MVC Razor 页面显示相关的表数据,并且似乎在我的页面模型 OnGetAsync 方法中的 LINQ .include 出现问题,或者在尝试在 Razor 中显示包含的内容时页面。
我们将不胜感激。如果我能提供更多相关信息,请告诉我。我现在才做 EFCore/RazorPages/Mvc/C# 几个月,所以请善待!
这是我包含子表的index.cshtml.cs 页面:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Appname.Models;
namespace Appname.Pages.Request
{
public class IndexModel : PageModel
{
private readonly Appname.Models.dbContext _context;
public IndexModel(Appname.Models.dbContext context)
{
_context = context;
}
public IList<ParentTable> ParentTable { get;set; }
public async Task OnGetAsync()
{
ParentTable = await _context.ParentTable
.Include(w => w.ChildTable)
.ToListAsync(); //Output to an async list
}
}
}
}
这是Index.cshtml razor 页面,其中嵌套的foreach 循环遍历Model.ParentTable[0].ChildTable 永远不会满足其条件,因为在调试期间检查Model.ParentTable[0].ChildTable 时计数为零,因此没有ChildField1 的数据或显示ChildField2:
@page
@model Appname.Pages.Request.IndexModel
@{
ViewData["Title"] = "Index";
}
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.ParentTable[0].ParentField1)
</th>
<th>
@Html.DisplayNameFor(model => model.ParentTable[0].ParentField2)
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.ParentTable)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.ParentField1)
</td>
<td>
@Html.DisplayFor(modelItem => item.ParentField2)
</td>
<td>
<table class="table">
<tr>
<th>Child Field 1</th>
<th>Child Field 2</th>
</tr>
@foreach (var relatedItem in Model.ParentTable[0].ChildTable)
{
<tr>
<td>
@Html.DisplayFor(modelItem => relatedItem.ChildField1)
</td>
<td>
@Html.DisplayFor(modelItem => relatedItem.ChildField2)
</td>
</tr>
}
</table>
</td>
<td>
<a asp-page="./Edit" asp-route-id="@item.ParentTableid">Edit</a> |
<a asp-page="./Details" asp-route-id="@item.ParentTableid">Details</a>
</td>
</tr>
}
</tbody>
</table>
这是ParentTable 模型:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Appname.Models
{
public partial class ParentTable
{
[Key]
public long ParentTableid { get; set; }
public string ParentField1 { get; set; }
public string ParentField2 { get; set; }
public ICollection<ChildTable> ChildTable { get; set; }
}
}
...以及ChildTable 模型,使用非标准 ID 命名约定用于 EF Core,因为这就是该字段在数据库中的设计方式,这是很久以前编写的(不确定这是否是问题或我的关键字段设置错误):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Appname.Models
{
public partial class ChildTable
{
public long nonstandardidfield { get; set; }
public string ChildField1 { get; set; }
public string ChildField2 { get; set; }
[ForeignKey("nonstandardidfield")]
public ParentTable ParentTable { get; set; }
}
}
感谢您的宝贵时间。
【问题讨论】:
标签: c# linq entity-framework-6 asp.net-core-mvc razor-pages