views:

228

answers:

3

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?

A: 

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)

Justin Niessner
+4  A: 

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.

Craig Stuntz
Lazy loading is not inefficient, it's situational. Sometimes lazy loading is more efficient than eager loading and sometimes it isn't, depending on the scenario. For example, if your table contains a large blob column that you don't need, lazy loading is more efficient. Eager loading can't be forced in EF1.
Michael Maddox
Michael, projection is a better fix for that. Lazy loading may seem efficient if you don't consider all the alternatives. I agree there are *cases* where lazy loading is the best solution, but it's the exception, not the rule.
Craig Stuntz
A: 

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 http://stackoverflow.com/questions/1618016/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).

Michael Maddox