首页 > 解决方案 > 显示来自一对多关系.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>
                }

标签: c#asp.net-mvc

解决方案


修复动作

 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>
                }
}

推荐阅读