Lazy loading not working in Entity Framework

2020-04-23 05:16发布

问题:

I have two classes that are connected by using the virtual keyword:

Student:

public class Student
{
    public int StudentId{get; set;}
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public DateTime EnrollmentDate { get; set; }
    public virtual IEnumerable<Enrollment> Enrollments { get; set; }
}

Enrollment:

public class Enrollment
{
    public int EnrollmentId { get; set; }
    public int CourseId { get; set; }
    public int StudentId { get; set; }
    public decimal? Grade { get; set; }
    public virtual Course course { get; set; }
    public virtual Student student { get; set; }
}

Both tables are populated, and have corresponding records (for instance, there is a student with id 1 and enrollments for student with id 1).

I'm pulling up a student by it's id and sending it to a view

Student student = db.Students.Find(id);
return View(student);

In the view I can display the details for that student. The @Model does contain an Enrollment property (at least it comes up in intellisense and doesn't red-line), but it is Null.

There is also a course class:

{
    public int CourseId { get; set; }
    public String CourseName { get; set; }
    public int TotalCredits { get; set; }
}

Since @Model.Enrollments is Null, I can't access @Model.Enrollment.CourseNamae.

Edit: I just tried a hack workaround:

IEnumerable<Student> temp = db.Students.Include(s => s.Enrollments);
Student student = temp.FirstOrDefault(s => s.StudentId.Equals(id));
return View(student);

This is giving me the error on the second line:

System.InvalidOperationException: A specified Include path is not valid. The EntityType 'MyFirstProject2.Models.Student' does not declare a navigation property with the name 'Enrollments'.

Does that offer any clues?

回答1:

A little bit late but here some explanation between Lazy Loading vs Eager Loading

And also the Rules for lazy loading:

  1. context.Configuration.ProxyCreationEnabled should be true.
  2. context.Configuration.LazyLoadingEnabled should be true.
  3. Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not define as virtual.

EDIT: One last thing for relationships use:

public virtual ICollection<Enrollment> Enrollments { get; set; }

Other Links:

Lazy Loading

Eager Loading

Explicit Loading