Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
            }
like image 754
Dmytro Bogatov Avatar asked Dec 24 '22 10:12

Dmytro Bogatov


1 Answers

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(...)...;
like image 102
octavioccl Avatar answered Dec 29 '22 05:12

octavioccl