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

时间:2015-01-18 16:23:46

标签: c# asp.net-mvc entity-framework

我已经找到了一些解决方案,但大多数是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发送到View页面,而是尝试发送Enrollments,然后调用其他类/表。同样的故事,出现错误,创建构造函数结果没有错误,但没有数据吃。

3 个答案:

答案 0 :(得分:1)

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

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没有参加任何课程,它也没有给我任何错误,它只是没有#&# 39; t包含任何数据,因此不会执行foreach循环。

答案 1 :(得分:1)

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

答案 2 :(得分:0)

检查您是否在

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

<强>的Global.asax.cs

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