c# - 显示来自一对多关系.net的数据
问题描述
首先,我是 c# 和 .net 的真正初学者,我从 10 天前开始,所以我试图显示一对多关系中的数据,但我有一个错误System.NullReferenceException:'对象引用未设置为对象的实例. (我检查了数据库,此表中有数据),我不明白为什么。我读了很多关于这个的帖子,但它从来没有用过,我的代码与 microsoft doc 页面上的示例几乎相同,但我的不起作用。
模型
[Display(Name = "Formations")]
public virtual ICollection<Courses> Course { get; set; }
}
public class Courses
{
[Key]
public int CourseId { get; set; }
[Display(Name = "Formations")]
public string Course { get; set; }
public virtual Users users { get; set; }
}
控制器
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var users = await _context.Users
.FirstOrDefaultAsync(m => m.Id == id);
if (users == null)
{
return NotFound();
}
return View(users);
看法
@foreach (var item in Model.Course)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Course)
</td>
</tr>
}
解决方案
修复动作
var users = await _context.Users.Include(i=>i.Course)
.FirstOrDefaultAsync(m => m.Id == id);
因为您使用的是 displayfor,所以您将不得不用 for 循环替换 foreach 循环
@model User
....
@if (Model.Course!=null)
{
@for (var i=0; i<= Model.Course.Count; i+=1)
{
<tr>
<td>
@Html.DisplayFor(model=> model.Course[i].Course)
</td>
</tr>
}
}
推荐阅读
- python - 如何解决关系“django_session”在具有firebase后端并部署在heroku上的django应用程序中不存在错误
- node.js - 在没有回调函数的 URL 中获取参数
- html - How to apply rvest to a dataframe column of HTML to make a column of extracted emboldened words
- powerapps - PowerAutomate Flow 在 PowerApps 编辑器中工作,但不能从 PowerApps 平板电脑应用程序启动
- overriding - Prestashop 1.7.7.1:覆盖控制器
- r - 为值向量编写 R 函数
- python - 如何返回在函数 A 中定义的列表以在 python 中的函数 B 中使用?
- r - 转向凌乱的数据
- python - 如何正确扭曲python中的文档图像?
- angular - 应用模块中的 Angular 动态 forRoot 值(基于 api)