开发者

Lazy loading, Deferred Loading and Eager Loading in Entity framework

What are the differences between these 3 types of loading? Can someone explain with an example? Different resources online use diffe开发者_Go百科rent definitions causing more confusion than necessary.


Lazy loading and Deferred are pretty synonymous (AFAIK, please correct me if I'm wrong). The big difference is between Eager and Lazy. Eager will happen up front, Lazy happens only "as needed" and execution will happen at the DB level- let's take a simple JOIN statement as an example

var people = (from p in people SELECT p).ToList();
var jobs = (from j in jobs SELECT j).ToList();

var peopleAndJobs = (from p in people JOIN j on j.personId equals p.personId SELECT p).ToList()

This is an example of eager loading. We are getting ALL people, ALL jobs, and we are doing the join in memory. Not very smart (usually). Here is what it looks like Lazy-style.

var people = (from p in people SELECT p);
var jobs = (from j in jobs SELECT j);

var peopleAndJobs = (from p in people JOIN j on j.personId equals p.personId SELECT p).ToList()

What this is doing is creating an IQueryable for both people and job (IQueryable is lazy), and the join is happening in the DB. This saves network activity, and is usually actually faster, since the DB is optimized to do joins and such.

Unless we explicitly say "I need that data!" (by ToListing it, iterating through it, etc) it's lazy. There are some more quirks but this should be a decent primer.


Lazy/Deferred Loading: Lazy loading and Deferred Loading are same thing. The relationship is loaded when it is accessed for the first time. The idea is that if the data is not required it should not be loaded.

Eager Loading: Relationship is fetched along with the Parent object. This can be more efficient in loading data but will load data irrespective of the data being used/notused.


When objects are returned by a query, related objects are not loaded at the same time.

Instead they are loaded automatically when the navigation property is accessed. Also known as “lazy loading,”

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜