导航属性,对象未设置为对象的实例

Navigation Properties, Object not set to an instance of an object

我已经找到了一些解决方案,但大多数是在 winforms、wpf 中。一些解决方案是关于 MVC 的,它不能解决我的问题。

我是按照 this tutorial.

创建的

控制器

public class NewPageController : Controller
{
    private SchoolContext db = new SchoolContext();

    public ActionResult ABC()
    {

        var Students = db.Students;

        return View(Students);
    }
 }

型号:

public class Student
{
    public int StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime EnrollmentDate { get; set; }
    //NavigationProperties
    public List<Enrollment> Enrollments { get; set; } 

}

public class Course
{
    public int CourseId { get; set; }
    public string CourseName { get; set; }
    public int TotalCredits { get; set; }
    //navigationProperties
    public List<Enrollment> Enrollments { get; set; } 
}

public class Enrollment
{
    public int EnrollmentId { get; set; }
    public int CourseId { get; set; }
    public int StudentId { get; set; }
    public decimal? Grade { get; set; } 

    //navigation properties
    public Student student { get; set; }
    public Course course { get; set; }
}

public class SchoolContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Course> Courses { get; set; }
    public DbSet<Enrollment> Enrollments { get; set; }
}

在学习教程时,他解释了如何使用初始化创建一些示例数据。现在我不是很喜欢这个,我还在努力了解如何去做。

我已经这样做了,像这样:

public class SchoolInitializer :DropCreateDatabaseIfModelChanges<SchoolContext>
{
    protected override void Seed(SchoolContext context)
    {
        var students = new List<Student>
        {
            new Student{FirstName = "James", LastName="Dean", EnrollmentDate = DateTime.Parse("10-01-2015")},
            new Student{FirstName = "Lison", LastName="Bergsma", EnrollmentDate = DateTime.Parse("05-01-2015")},
        };
        foreach(var temp in students)
        {
            context.Students.Add(temp);
        }
        context.SaveChanges();

        var courses = new List<Course>
        {
            new Course{CourseName = "Java", TotalCredits=4},
            new Course{CourseName = "C#", TotalCredits=4},
        };
        foreach (var temp in courses)
        {
            context.Courses.Add(temp);
        }
        context.SaveChanges();

        var enrollments = new List<Enrollment>
        {
            new Enrollment{StudentId=1,CourseId=1, Grade =3},
            new Enrollment{StudentId=1,CourseId=2, Grade =4},
        };
        foreach (var temp in enrollments)
        {
            context.Enrollments.Add(temp);
        }
        context.SaveChanges();

    }
}

观看次数

这里是我遇到异常的地方,当我尝试为 item.Enrollments 执行 foreach 时。

@model IEnumerable<ProjectName.Models.Student>

@foreach (var item in Model)
{
    <h2> Student : @item.FirstName @item.LastName</h2>
    foreach (var i in item.Enrollments)
    {
        <h2>Course: @i.course.CourseName</h2>
    }
    <br />
}

正如许多人建议的那样,我尝试在模型中创建构造函数,并创建 Enrollments 对象的新实例。这样做时,它没有给我任何错误,但也没有加载任何数据。我没有将 Students 发送到查看页面,而是尝试发送注册,然后调用另一个 classes/tables。同样的故事,出现错误,创建构造函数导致没有错误但没有数据吞噬器。

指定要包含在查询结果中的相关对象。

public class NewPageController : Controller
{
    private SchoolContext db = new SchoolContext();

    public ActionResult ABC()
    {

        var Students = db.Students.Include("Enrollments.course"); //edit by OP

        return View(Students);
    }
 }

OP编辑:

我已经编辑了上面的代码并在我的解决方案中包含了下面的代码。

@model IEnumerable<vergelijkCuracao.Models.Student>

@foreach (var item in Model)
{
    <h2> Student : @item.FirstName @item.LastName</h2>
    if (item.Enrollments != null)
    {
        foreach (var i in item.Enrollments)
        {
            <h2> Course : @i.course.CourseName</h2>
        }
    }

}

我必须指出,在这个例子中 if 检查并不是真正需要的,即使学生 2 没有注册任何课程,它也没有给我任何错误,它只是没有' t 包含任何数据,因此不会执行 foreach 循环。

@model IEnumerable<ProjectName.Models.Student>

@foreach (var item in Model)
{
    <h2> Student : @item.FirstName @item.LastName</h2>
    if (item.Enrollments!=null)
    {
       foreach (var i in item.Enrollments)
       {
          <h2>Course: @i.course.CourseName</h2>
       }
      <br />
    }
}

检查您是否在

的 Application_Start() 方法中实际初始化了 DbContext

Global.asax.cs

protected void Application_Start(){
    Database.SetInitializer<SchoolContext>(new SchoolInitializer());
    AreaRegisration.RegisterAllAreas();
    ...
}