Lazy Loading vs. Explicit Loading Eager Loading

  • 2382
  • 0
  • 2011-10-17

Lazy Loading vs. Explicit Loading Eager Loading

Lazy Loading 延遲載入,又稱just-in time loading, lazy initialization, on-demand loading, deferred loading.

在Entity Framework 4, lazy loading 是預設啟用的。

 

Lazy Loading: Lazy loading of data is also called just-in-time loading, when the data does not load until you reference it.

Eager Loading: Eager loading is using the Include extension method to load child table data when the parent table is being loaded.

Explicit loading: Explicit loading of data is using the Load extension method explicitly to load child table data before you use it.

 

說明參考:http://www.dotblogs.com.tw/programlin/archive/2010/10/14/18337.aspx

範例參考:http://weblogs.asp.net/dotnetstories/archive/2011/03/10/lazy-loading-eager-loading-explicit-loading-in-entity-framework-4.aspx

範例練習所需資料表與資料:

備註:因為此範例是把EDM放到獨立專案,然後從Web Site專案參考使用,直接執行會產生「指定的具名連接在此組態中找不到、不應使用於 EntityClient 提供者,或者無效。」例外錯誤。請參考Will 大寫的這篇:關於 Entity Framework 獨立放在 DAL 專案的注意事項

做了上面這個範例,但還是搞不懂explicit loading 跟 lazy loading 有甚麼差別...

 

 

 

今天看到一題 70-516的考古題


{
	public int CategoryID{get; set;}
	public string CategoryName{get; set;}
	public string Description{get; set;}
	public byte[] Picture{get; set;}
	public virtual List<Product> Products{get; set;}
}

為什麼第7行Products 集合屬性要加上virtual 關鍵字 才能支援deferred loading (lazy loading)?

 

我找到一篇簡中的說明:「当 EF 访问实体的子实体的时候是如何工作的呢?你的集合是 POCO 的集合,所以,在访问的时候没有事件发生,EF 通过从你定义的实体派生一个动态的对象,然后覆盖你的子实体集合访问属性来实现。这就是为什么需要标记你的子实体集合属性为 virtual 的原因。」,不過....有看沒有懂!

 

幸好這段文字是翻譯版,所以請看原文:「

Now lazy loading works as you would expect: you request an entity-set, it gets loaded and if you try to access a sub-collection of an entity, it gets loaded on the fly, auto-magically!

How does EF knows you’re trying to access a sub collection? You collection are POCO collection (e.g. List<EntityType>), so no events are raised if you access them. Anyone? It’s generating a dynamic object deriving from your entities and override your sub-collection access properties. Yes it does. This is why you need to mark your sub-collection access properties with the keyword virtual in order for the magic to operate:

簡中:http://www.cnblogs.com/haogj/archive/2011/05/07/2039620.html

原文:http://vincentlauzon.wordpress.com/2011/04/11/entity-framework-4-1-deep-fetch-vs-lazy-load-3/