I have created two model classes: Student
and Exam
.
Student:
class Student
{
[Key]
public int StudentId { get; set; }
[Required, MaxLength(30)]
public string FirstName { get; set; }
[Required, MaxLength(50)]
public string LastName { get; set; }
[Required]
public DateTime BirthDate { get; set; }
public virtual ICollection<Exam> Exams { get; set; }
}
Exam:
public enum Grade
{
A, B, C, D, E, F
}
class Exam
{
[Key]
public int ExamId { get; set; }
[Required]
public Grade Grade { get; set; }
[ForeignKey("Student"), Required]
public int StudentId { get; set; }
public virtual Student Student { get; set; }
}
But it seems Lazy Loading doesn't work, here's example how I retrieve data:
using (var context = new StudentContext())
{
context.Configuration.LazyLoadingEnabled = true;
context.Configuration.ProxyCreationEnabled = true;
var student = context.Students.Single(s => s.LastName == "ABC");
foreach (var exam in student.Exams)
{
Console.WriteLine($"{exam.ExamId}: {exam.Grade}");
}
context.SaveChanges();
}
And I'm getting NullReferenceException
when I try to access students.Exams
property. What's wrong in my code?
The problem with my code is that Entity Framework Lazy Loading isn't working and I don't know why. It's not about not initializing Exams
, because Entity Framework should do it alone when I try to access Exams
property.