我試圖讓Department
對象的Studies
屬性延遲加載,但它只會在我急切加載時加載。我已將DepartmentId
添加到Study
級別,但沒有結果,使用了ICollection
,ISet
和virtual
。公共和私人的制定者似乎沒有什麼區別(也不應該)。似乎沒有任何工作。使用EF 6.1。實體框架急切加載關聯的集合,但不會延遲加載它
public class Department
{
private Department() {}
public Department(DepartmentTitle title)
{
if (title == null) throw new ArgumentNullException();
this.Title = title;
this.Studies = new HashSet<Study>();
}
public int DepartmentId { get; private set; }
public virtual DepartmentTitle Title { get; private set; }
public virtual ICollection<Study> Studies { get; set; }
}
public class Study
{
private Study() {}
public Study(StudyTitle title, Department department)
{
if (title == null) throw new ArgumentNullException();
if (department == null) throw new ArgumentNullException();
this.Title = title;
this.Department = department;
}
public int StudyId { get; private set; }
public virtual StudyTitle Title { get; private set; }
public virtual Department Department { get; set; }
}
// Here I save the department and study objects
// I verified they exist in the database
var department = new Department(new DepartmentTitle("Department Title Here"));
department.Studies.Add(new Study(new StudyTitle("Study Title Here"), department));
data.SaveChanges();
// In a new database context
// Here I try to lazy load the Studies property, but get null
// It works if I add Include("Studies") before Where()
Department department = data.Departments.Where(d => d.Title.Value == "Department Title Here").Single();
System.Console.WriteLine(department.Studies.First().Title.Value);
// DepartmentTitle and StudyTitle are simple complex types with a Value property
這很奇怪,但它的工作原理。我認爲它沒有什麼區別,因爲它告訴我們EF如何使用反射來訪問任何需要的東西。顯然不是。 – Seralize
我希望在幾個星期前我偶然發現了這個問題。試圖弄清楚爲什麼懶加載不適用於我的實體。我在我的實體上有一個私有的無參數構造函數,它可以很好地與EF一起從數據庫加載實體。將其更改爲受保護,並延遲加載最終有效。 !AARGH – TheOtherTimDuncan