如果从表StudentsSubject
删除Id
场然后从模型中删除该表并更新你的模型,EF会自动将这个表有两种导航性能Subjects
和Students
分别为Student
和Subject
实体。
如果你必须离开StudentsSubject表架构完整,您可以使用Include()
方法来获得学生和他们的臣民:
var students = dbContext.Students.Include("StudentsSubject.Subject")
随着“正常”的导航属性,你可以写:
var students = dbContext.Students.Include("Subjects")
有时您需要组装大图,然后Include()和延迟加载会影响性能。有这种情况下的小窍门:
// switch off for performance
DbContext.Configuration.AutodetectChangesEnabled = false;
// load root entities
var roots = dbContext.Parents.Where(root => %root_condition%).ToList();
// load entities one level lower
dbContext.DependentEntities.Where(dependent => dependent.Root%root_condition% && %dependent_condition%).ToList();
// detect changes
dbContext.ChangeTracker.DetectChanges();
// enable changes detection.
DbContext.Configuration.AutodetectChangesEnabled = true;
现在root.Dependents
藏品都充满了roots
。
这是加入冗余(包括或连接)和几个db请求之间的折衷,以及请求的复杂性不断增加。
对于加入节点的“包含”数据是重复的,因此一连串包含可以产生从数据库到客户端的巨大流量。
第二种方法的每个级别都要求Where()中的所有较高级别的过滤条件,EF为第N级别生成N-1个连接的查询,但没有冗余的地方。
据我知道现在EF工作正常载有()和父节点的条件可以用Contains()
取代:
// load root entities
var roots = dbContext.Parents.Where(root => %root_condition%).ToList();
var rootIds = new List<int>(roots.Select(root => root.Id));
// load entities one level lower
dbContext.DependentEntities.Where(dependent => %dependent_condition% && rootIds.Contains(dependent.RootId)).ToList();
为什么你不只是在你的'Student'模型添加另一个属性,获取他的主题,以便主题自动加载? – sed