Dot-Net
實體框架:導航屬性問題
我正在使用實體框架程式碼優先,並且我有一個
Course具有導航屬性的類Students:public virtual Collection<Student> Students { get; set;}它工作正常,但是當我訪問此導航屬性時,所有數據都從數據庫中檢索:
var allStudents = course.Students; // Here it retrieves the data var activeStudents = allStudents.Where(n => n.Active); // Here it filter the data on memory var listOfActiveStudents = activeStudents.ToList(); // It already has the data on memory.正如您所想像的那樣,我需要在執行查詢時執行查詢,
.ToList()因為我不想Students從數據庫中獲取所有資訊,而只獲取活動的查詢。你知道我做錯了什麼嗎?
延遲載入將整個集合載入到記憶體中。
virtual如果您不希望這樣,請通過刪除關鍵字來關閉延遲載入並使用 Query 對象DbEntry:public GetCourseWithActiveStudentsLoaded(int courseid) { var course= context.Courses.Find(courseid); context.Entry(course) .Collection(c => c.Students) .Query() .Where(s => s.Active) .Load(); return user }“活動”標誌是否表明您正在嘗試實施軟刪除?如果是這樣,這裡有一個解決方案:實體框架中的軟刪除
您可以在此處為已過濾的包含投票:允許過濾包含擴展方法
另一種方法是繼承。您可以在類中具有
ActiveStudent繼承自Student和ActiveStudents導航屬性以及AllStudents導航屬性Coursepublic virtual Collection<Student> AllStudents { get; set;} public virtual Collection<ActiveStudent> ActiveStudents { get; set;}參考: