如果從表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