EF:同时包含导航属性和排除子导航属性

时间:2016-01-10 18:16:42

标签: c# entity-framework navigation-properties

我有两个实体:

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

我在DBContext中描述它们:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Exam>()
        .HasRequired(d => d.PStudent)
        .WithMany(d => d.PExams)
        .HasForeignKey(d => d.PStudentId);
}

我关闭延迟加载Configuration.LazyLoadingEnabled = false;并在DBContext中为Exam and Student添加了属性。

public DbSet<Exam> Exams { get; set; }
public DbSet<Student> Students { get; set; }

现在我试着拿到考试清单。

await m_DataContext.Exams.ToListAsync();

此代码为我提供了带有空属性PStudent的考试列表(如预期的那样)。所以我将代码更改为下一个:

await m_DataContext.Exams.Include(d=>d.PStudent).ToListAsync();

我预计我将收到填写属性PStudent的考试列表,PStudent的属性PExams将为空,但它有数据(考试列表)。当我包含主导航属性时,如果将子导航属性保留为空,我应该更改什么?

1 个答案:

答案 0 :(得分:1)

这是预期的行为。

EF会填充加载到跟踪图中的所有导航属性。什么.Include确实告诉EF在导航属性的末尾加载实体并跟踪它,然后它会自动传播到实体中。

您已经将Exam实体作为查询的一部分加载,因此会自动填充链接和反向。

我有一种怀疑(但尚未尝试过),如果使用m_DataContext.Exams.AsNoTracking().Include(d=>d.PStudent),则可能无法填充反向属性,但这实际上取决于内部如何实施AsNoTracking。

相关问题