I have two entities:
public class Student
{
public int Id { get; set; }
public virtual ICollection<Exam> PExams { get; set; }
}
public class Exam
{
public int Id { get; set; }
public DateTime Date { get; set; }
public int PStudentId { get; set; }
public virtual Student PStudent { get; set; }
}
I describe them in DBContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Exam>()
.HasRequired(d => d.PStudent)
.WithMany(d => d.PExams)
.HasForeignKey(d => d.PStudentId);
}
I turn off lazy loading Configuration.LazyLoadingEnabled = false;
and added properties for Exam and Student in DBContext.
public DbSet<Exam> Exams { get; set; }
public DbSet<Student> Students { get; set; }
and now I tried to get the list of Exam.
await m_DataContext.Exams.ToListAsync();
This code gets me the list of Exam with empty properties PStudent (as expected). So I changed my code to next:
await m_DataContext.Exams.Include(d=>d.PStudent).ToListAsync();
I am expected that I will receive the list of Exam with filled property PStudent and property PExams of PStudent will be empty, but it has data (a list of Exam). What should I change for leaving sub navigation property empty when I included main navigation property?
This is expected behavior.
EF populates any navigation properties which are loaded into the tracking graph. What .Include does is tells EF to load the entity at the end of the navigation property and also tracks it, then it is automagically propagated into the entity.
You have already loaded the Exam entity as part of the query so the link and reverse are automatically populated.
I have a suspicion (but haven't tried it out) that if you use m_DataContext.Exams.AsNoTracking().Include(d=>d.PStudent)
the reverse property may not be populated but it really depends on how AsNoTracking is implemented internally.