[英]EF: Include navigation property and exclude sub navigation property in same time
我有两个实体:
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中添加了考试和学生的属性。
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将为空,但其中包含数据(考试列表)。 当包含主导航属性时,如何将子导航属性留空?
这是预期的行为。
EF填充加载到跟踪图中的所有导航属性。 .include的作用是告诉EF在导航属性的末尾加载实体并对其进行跟踪,然后将其自动传播到实体中。
您已经将Exam实体作为查询的一部分加载,因此将自动填充链接和反向链接。
我怀疑(但尚未尝试过)如果您使用m_DataContext.Exams.AsNoTracking().Include(d=>d.PStudent)
则反向属性可能不会被填充,但这实际上取决于如何实现AsNoTracking内部。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.