我已经开始将我的“超级”语境分解成更小的重点语境。在一个简单的场景中,我Student
和Lectures
POCOS 和我EntityTypeConfiguration
在一个名为StudentsAndLectures
.
这些表是在我的 uber 上下文中定义的表关系网络的一部分。但是,我想以更有针对性的方式和有针对性的背景来管理学生和他们的讲座。
下面是我的 POCO 课程。
public class Student
{
public Student()
{
Lecture = new List<Lecture>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Lecture> Lectures { get; set; }
}
public class Lecture
{
public Lecture()
{
Students = new List<Student>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
最后,我的实体类型映射器。
public class StudentMapper : EntityTypeConfiguration<Student>
{
public StudentMapper()
{
HasKey(x => x.Id);
HasMany(x => x.Lectures)
.WithMany(x => x.Students)
.Map(m =>
{
m.MapLeftKey("LectureId");
m.MapRightKey("StudentId");
m.ToTable("StudentsAndLectures");
});
Property(x => x.Name);
}
}
public class LectureMapper : EntityTypeConfiguration<Lecture>
{
public LectureMapper()
{
HasKey(x => x.Id);
HasMany(x => x.Students)
.WithMany(x => x.Lectures)
.Map(m =>
{
m.MapLeftKey("LectureId");
m.MapRightKey("StudentId");
m.ToTable("StudentsAndLectures");
});
Property(x => x.Name);
}
}
此外,My Focused context 包含仅适用于学生和讲座的 DbSet。
我的问题,如果我使用我的重点上下文查询如下特定学生,我的 .Lectures 导航属性返回空。但是,如果我使用创建数据库的完整(超级)上下文,我的导航属性会按照我的意愿延迟加载或急切加载。有谁知道为什么会这样?
using(FocusedStudentContext db = new FocusedStudentContext())
{
var student = db.Students.Include(s => s.Lectures)
.FirstOrDefault(s => s.StudentID == 1234);
// Inspecting student here for the Lectures navigation property
// collection has 0 elements.
}
经过进一步的测试和实验,我发现如果我包含一个DbSet
存在于我的模型中的特定(非其他)附加组件及其相关ModelBuilder
配置,那么一切正常。DbSet
是一个实体, ,它是一个Registration
具有导航属性的实体。另一个转折是,如果我保留实体的配置,但从我的重点上下文中删除,那么我的导航属性将停止再次添加。(该集合有 0 个元素)。Student
HasRequired (x => x.Student)
ModelBuilder
Registration
DbSet<Registration>
Lectures
我的困惑是,DbSet
在我的重点上下文中添加一个如何影响我的导航属性为上述表/实体解析的方式?我该如何解决这个问题。任何帮助将不胜感激。