Database Reference
In-Depth Information
{
Console.WriteLine("\t{0}", email.Email);
}
}
// Extra credit:
// If you enable SQL Profiler, the following query will not requery the database
// for related data. Instead, it will return the in-memory data from the prior query.
foreach (var customer in customers)
{
Console.WriteLine("{0} is a {1}, email address(es)", customer.Name,
customer.CustomerType.Description);
foreach (var email in customer.CustomerEmails)
{
Console.WriteLine("\t{0}", email.Email);
}
}
}
The output of the code in Listing 5-1 is the following:
Customers
=========
Customer name is Joan Smith
Customer name is Bill Meyers
Joan Smith is a Web Customer, email address(es)
jsmith@gmail.com
joan@smith.com
Bill Meyers is a Retail Customer, email address(es)
bmeyers@gmail.com
Joan Smith is a Web Customer, email address(es)
jsmith@gmail.com
joan@smith.com
Bill Meyers is a Retail Customer, email address(es)
bmeyers@gmail.com
How It Works
By default, Entity Framework loads only entities that you specifically request. This is known as lazy loading , and it
is an important principle to keep in mind. The alternative, loading the parent and every associated entity, known as
eager loading, may load a much larger object graph into memory than you need, not to mention the added overhead
of retrieving, marshaling, and materializing a larger amount of data.
In this example, we start by issuing a query against the Customer entity to load all customers. Interestingly, the
query itself is not executed immediately, but rather when we first enumerate the Customer entity in the first foreach
construct. This behavior follows the principle of deferred loading upon which LINQ is built.
In the first foreach construct, we only request data elements from the underlying Customer table and not any
data from the CustomerType or CustomerEmail table. In this case, Entity Framework only queries the Customer table
and not the related CustomerType or CustomerEmail tables.
Then, in the second foreach construct, we explicitly reference the Description property from the CustomerType entity
and the Email property from the CustomerEmail entity. Directly accessing these properties results in Entity Framework
generating a query to each related table for the requested data. It's important to understand that Entity Framework generates
 
 
Search WWH ::




Custom Search