By default, LINQ objects are loaded in a deferred nature;
this means that any child objects of a parent are not loaded until they are
accessed. So for the Customer object, once the Orders collection is accessed,
these orders are loaded at this point, rather than loading them all at the same
time. This means another database query pulls back the orders data, involving
two hits to the database.
However, it is possible that loading the parent data also
loads the child data immediately, using the following setup.
Listing 10
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Employee>(i => i.EmployeePositions);
_context.LoadOptions = options;
The DataContext class has a LoadOptions property that
specifies any children to load for a given parent. So, when loading employee
information, any related records in EmployeePositions (a join table designed
for a many-to-many join situation) are also loaded. This prevents a second
query for any relationship data. You must define load options before querying
against the context.
You may wonder whether that is better; really, it depends on
your situation. I cannot say that in every situation, immediate loading is a
better approach. Sometimes, you do not need all of the related data, so a
deferred approach is better. However, other times, you will use all of the
employee and related position records, and so immediate loading would help
reduce the number of calls to the database.
Ideally, it is the number of database calls that immediate
loading is trying to reduce, and whether that really reduces the number of
calls depends on the type of application, the size of the data coming back, the
relationships between the data, etc.