我再次有以下兩類,由我的測試模型產生:延遲加載不起作用
public partial class House
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public House()
{
this.Persons = new HashSet<Person>();
}
public int id { get; set; }
public string street { get; set; }
public string city { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Person> Persons { get; set; }
}
public partial class Person
{
public int id { get; set; }
public string namen { get; set; }
public int house { get; set; }
public virtual House House1 { get; set; }
}
在我的DbContext的構造函數中我明確地啓用延遲加載,什麼甚至不應該必要:
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ProxyCreationEnabled = true;
後來我把房子的列表:
YardEntities cx = new YardEntities();
IList<House> hl = cx.Houses.ToList<House>();
House h = hl[0];
///**************BREAKPOINT*******************///
Person g = h.Persons.First<Person>();
output = g.namen;
標記b之後我預計,由於延遲加載,所有與房屋有關的人都是而不是。我沒有訪問一個人,所以他們爲什麼要加載?但是它們被加載,因爲我的調試器顯示了所有的名稱屬性。
有人可以解釋這種行爲嗎?爲什麼懶加載不起作用?
我想因爲你用的是.. cx.Houses.ToList();不要做toList(),你會得到數據 –
lordkain
不 - 這是官方教程,它也使用tolist()http://www.entityframeworktutorial.net/EntityFramework4.3/lazy-loading-with-dbcontext .aspx – David
來幽默我,嘗試沒有tolist – lordkain