Entity Framework 6 Lazy Loading doesn't work

c# entity-framework entity-framework-6

Question

Two model classes that I developed are: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; }
}

However, it appears that Lazy Loading is ineffective. Here is an example of 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 acquiringNullReferenceException my attempts to accessstudents.Exams property. Why is my code flawed?

Entity Framework Lazy Loading isn't functioning in my code, and I'm not sure why. It is not about failing to initializeExams when I try to access Entity Framework, it should do it alone.Exams property.

1
3
3/22/2016 11:11:12 PM

Accepted Answer

ZZZ_tmp
11
3/23/2016 7:50:40 AM

Popular Answer

If you don't declare access modifiers in C#, it will automatically accept them as internal.

Declare your entity classes to be public.

In addition to returning null, collections should also return empty collections. Because of this, you should return an empty collection if a student has no exams. This is the reason why you should also modify your student constructor.

 public class Student
    {
        public Student()
        {
            Exams = new List<Exam>();
        }
    }

Edit: When you haveICollection or IList , ef returns a collection of nothing. Utilizing this constructor is recommended if you are usingIEnumurable .



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow