EF 7: How to load related entities in a One-to-many relationship

asp.net asp.net-core c# entity-framework entity-framework-core

Question

I have the following code. Why are my navigation properties (Requirement in Course, and Courses in Requirement) are null?

    public class Course : AbsEntity {
            [Key]
            public string Title { get; set; }
            public string Term { get; set; }
            public int Year { get; set; }
            public string CourseId { get; set; }        
            public double GradePercent { get; set; }        
            public string GradeLetter { get; set; }     
            public string Status { get; set; }
            public int ReqId { get; set; }

            public Requirement Requirement { get; set; }
        }

    public class Requirement : AbsEntity {
            [Key]
            public int ReqId { get; set; }
            public string ReqName { get; set; }

            public ICollection<Course> Courses { get; set; }
        }

// In DbContext
    protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Course>().HasOne(c => c.Requirement).WithMany(r => r.Courses).HasForeignKey(c => c.ReqId);
                modelBuilder.Entity<Requirement>().HasMany(r => r.Courses).WithOne(c => c.Requirement);
            }

Accepted Answer

First thing is you don't need to configure your relationship twice, you just need to do it one time:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   modelBuilder.Entity<Course>().HasOne(c => c.Requirement)
                                .WithMany(r => r.Courses)
                                .HasForeignKey(c => c.ReqId);          
}

Second thing is if you are doing a query and you are expecting to lazy load the related properties, I'm afraid is not going to be possible. EF 7 doesn't support lazy loading yet. As you can see there is a backlog item tracking Lazy Loading. So, if you need to load a related entity, you should use explicit loading using Include method:

 var query= ctx.Courses.Include(c=>c.Requirement).Where(...)...;


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why