简体   繁体   中英

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);
            }

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(...)...;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM