Tutorial :Entity Framework - When does it load referenced relationships automatically?


In what instances does Entity Framework automatically load child rows and other related rows as you use them? It seems like sometimes this is done automatically on property accessor, and sometimes you must do it explicitly.

For example, if I have a table called Car, and a table called Wheel, and there are 4 wheels rows for each car row, will EF automatically load the Wheel rows when I access myCar.Wheel, or is the general practice to call myCar.Wheel.Load() first?


In EF 4, lazy loading is done by default if you use code generation or proxies. "Pure" POCOs (not to be confused with so-called POCO proxies) can't do lazy loading unless you code for it. More details are in this post.

In EF 1, there is no lazy loading, so you must use explicit loading, eager loading, or projection.

Explicit loading means calling Load(). You generally test IsLoaded before calling Load().

Eager loading causes the property to be loaded along with the entity itself. This avoids a second DB query.

Projection causes the EF to generate SQL for only the properties you need, in an optimized way.

Although lazy loading is on by default in EF 4, it is relatively inefficient in any ORM (causes many DB queries). You may still want to use projection or eager loading instead.


When using Entity Framework, the general practice is to check to see if the child is loaded...and if not, load it.

if (!order.SalesOrderDetail.IsLoaded)  {      order.SalesOrderDetail.Load();  }  

Straight from:

How to: Explicity Load Related Objects (Entity Framework)


In Entity Framework version 1 (aka 3.5), there are only three scenarios where EF is likely to load data from a related table:

  1. You explicitly join to that table in your Linq query
  2. You use the Include syntax in your Linq query (see Linq-To-Entities Include)
  3. You use projection as described in Craig Stuntz's answer.

All three of the scenarios described above require you to explicitly specify that you want related table data loaded. As far as I know EF v1 will never do it "behind the scenes" without you requesting it (which can be seen as a positive, but it's not how other modern ORMs work and they changed it in version 2 - aka version 4.0).

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »