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

Question

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

Answers 2
Added at 2016-01-11 20:01
Tags
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);
            }
Answers
nr: #1 dodano: 2016-01-11 21:01

Because name your property is incorrect. Rename

public int ReqId { get; set; }

to

public int RequirementId { get; set; }

And you can use lazy loading:

public virtual Requirement Requirement { get; set; }
nr: #2 dodano: 2016-01-11 21:01

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(...)...;
Source Show
◀ Wstecz