我想问一下如何在我的案例中包括数据。我创建了一个关联表,用于定义BusinessGlosItems
之间的关系。在下一步中,我创建了BusinessGlosItems
模型,并通过子级和父级关系包括了引用表。
最后,我需要显示BusinessGlosItems
的详细信息及其所有关联数据。听起来很简单,但我不知道该如何解决。有人可以帮忙吗?
我的域类如下:
public class BusinessGlosItem
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string BGIName { get; set; }
[InverseProperty("ChildBGItem")]
public ICollection<Reference> ChildReferences { get; set; }
[InverseProperty("ParentBGItem")]
public ICollection<Reference> ParentReferences { get; set; }
}
public class Reference
{
public int Id { get; set; }
[ForeignKey("ChildBGItem")]
public int? ChildGlosItemId { get; set; }
[ForeignKey("ParentBGItem")]
public int? ParentGlosItemId { get; set; }
public int ReferenceTypeId { get; set; }
public virtual ReferenceType ReferenceType { get; set; }
public virtual BusinessGlosItem ChildBGItem { get; set; }
public virtual BusinessGlosItem ParentBGItem { get; set; }
}
我想做什么:
@page
@model BusinessGlosItem.DetailsModel
<div>
<table class="table table-hover">
<th>Reference Type</th>
<th>Parent Item Name</th>
<th>Child Item Name</th>
@foreach (var item in Model.BusinessGlosItem.ParentReferences)
{
<tr>
<td>@item.ReferenceType.ReferenceTypeName</td>
<td>@item.ParentBGItem.BGIName</td>
<td>@item.ChildGlosItemId</td> //Here I would like to see the ChildItem Name
</tr>
}
</table>
</div>
我从视图中得到NullReferenceException: Object reference not set to an instance of an object. on the line
。
我的方法是:
public BusinessGlosItem BusinessGlosItem { get; set; }
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
BusinessGlosItem = await _context.businessGlosItem
.Include(x => x.BusinessArea)
.Include(x => x.BusinessGlosItemStatus)
.Include(x => x.ChildReferences).ThenInclude(x=>x.ReferenceType)
.Include(x => x.ParentReferences).ThenInclude(x=>x.ReferenceType)
.Include(x=>x.businessGlosItemComments)
.SingleOrDefaultAsync(m => m.Id == id);
if (BusinessGlosItem == null)
{
return NotFound();
}
return Page();
}
非常感谢!
答案 0 :(得分:2)
您忘记为ThenInclude
和ChildBGItem
的{{1}}和ParentBGItem
都提到ChildReferences
。因此,您的查询应如下所示:
ParentReferences
现在应该可以了。