Database Reference
In-Depth Information
Console.WriteLine("\nCustomers by Type");
Console.WriteLine("=================");
foreach (var customerType in customerTypes)
{
Console.WriteLine("Customer type: {0}", customerType.Description);
foreach (var customer in customerType.Customers)
{
Console.WriteLine("{0}", customer.Name);
foreach (var email in customer.CustomerEmails)
{
Console.WriteLine("\t{0}", email.Email);
}
}
}
}
The output of the code in Listing 5-2 is the following:
Customers
=========
Joan Smith is a Web Customer, email address(es)
Bill Meyers is a Retail Customer, email address(es)
Customers by Type
=================
Customer type: Web Customer
Joan Smith
Customer type: Retail Customer
Bill Meyers
How It Works
By default, Entity Framework loads only entities that you specifically request. This is known as
lazy loading
and can
be quite efficient in the use case where a user is browsing your application and may navigate to different views based
upon his or her needs.
An alternative, loading the parent and related entities (keep in mind that our object graph is a set of parent/child
entities based on relationships, similar to parent/child database tables with foreign key relationships) at once, is known
as
eager loading.
This approach can be efficient when you know, up front, that you will require a large set of related
data, as it can retrieve all data (both from the parent and related entities) in a single query.
In Listing 5-2, to fetch the object graph all at once, we use the
Include()
method twice. In the first use, we start
the object graph with Customer and include an entity reference to the CustomerType entity. This is on the
one
side
of the one-to-many association. Then, in the subsequent
Include()
method (contained in the same line of code,
chained together), we get the
many
side of the one-to-many association, bringing along all of the instances of the