2

I am learning EF6 with MVC 5 following this tutorial. I understand this question may have been asked, however I am not sure what exactly I need to be looking for? I checked the db and data is in there? Can anyone point me in the right direction?

I have an issue where in my Model.Enrollments is null(this view takes a student model), however in the database it shows it has values in that table.

Model: Student

public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }

Course

  public int ID { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public ICollection<Enrollment> Enrollments { get; set; }

Enrollment

public int ID { get; set; }
public decimal? Grade { get; set; }
public int StudentID { get; set; }
public int CourseID { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }

Exception:

An exception of type 'System.NullReferenceException' occurred in App_Web_uycs14gs.dll but was not handled in user code

enter image description here Additional information: Object reference not set to an instance of an object.

Database: enter image description here

Update- Context

  public DbSet<Student> Students { get; set; }
       public DbSet<Course> Courses { get; set; }
       public DbSet<Enrollment> Enrollments { get; set; }
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Harry
  • 3,031
  • 7
  • 42
  • 67

1 Answers1

3

You need to change your navigation properties as virtual if you want to be lazy loaded.

public class Student
{
   //...
   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public class Course
{
  //...
  public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public class Enrollment
{
  //...
  public virtual Student Student { get; set; }
  public virtual Course Course { get; set; }
}

Check this post for a better explanation. When you are using POCO entity types, lazy loading is achieved by creating instances of derived proxy types and then overriding virtual properties to add the loading hook.

Community
  • 1
  • 1
ocuenca
  • 38,548
  • 11
  • 89
  • 102