Я хотел бы спросить, как включить данные в моем случае. Я создал ассоциативную таблицу, в которой определяю отношения между 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();
}
Заранее большое спасибо!
да, мне нужно увидеть имя как дочернего, так и родительского элемента
Хорошо! Теперь скажите мне, что не так с вашим существующим кодом?
когда я выполняю этот код: @foreach (элемент var в Model.BusinessGlosItem.ParentReferences) { <tr> <td>@item.ReferenceType.ReferenceTypeName</td> <td>@item.ParentBGItem.BGIName</td> <td >@item.ChildBGItem.BGIName</td> //Здесь я хотел бы видеть имя ChildItem </tr> } Я получаю эту ошибку: NullReferenceException: Ссылка на объект не указывает на экземпляр объекта. в строке <td>@item.ChildBGItem.BGIName</td>





Вы забыли упомянуть ThenInclude как для ChildBGItem, так и для ParentBGItem как в ChildReferences, так и в ParentReferences. Таким образом, ваш запрос должен быть следующим:
BusinessGlosItem = await _context.businessGlosItem
.Include(x => x.BusinessArea)
.Include(x => x.BusinessGlosItemStatus)
.Include(x => x.ChildReferences)
.ThenInclude(x=>x.ReferenceType)
.Include(x => x.ChildReferences) // You missed this include
.ThenInclude(x=>x.ChildBGItem)
.Include(x => x.ChildReferences) // You missed this include
.ThenInclude(x=>x.ParentBGItem)
.Include(x => x.ParentReferences)
.ThenInclude(x=>x.ReferenceType)
.Include(x => x.ParentReferences) // You missed this include
.ThenInclude(x=>x.ChildBGItem)
.Include(x => x.ParentReferences) // You missed this include
.ThenInclude(x=>x.ParentBGItem)
.Include(x=>x.businessGlosItemComments)
.SingleOrDefaultAsync(m => m.Id == id);
Теперь это должно работать.
Вы пытаетесь показать детали
BusinessGlosItemс егоChildReferencesиParentReferences, не так ли? или что-то большее, чем это?