Database Reference
In-Depth Information
In the block of code, we create a few workers and assign them accidents of varying levels of severity. Granted, it's
a little creepy to assign accidents to people, but it's all in the name of getting some data with which you can work.
In the subsequent query, we select from all of the workers and project the results into an anonymous type. The
type includes the worker and the collection of accidents. For the accidents, notice how we filter the collection to get
just the serious accidents.
The very next line is important. Here we force the evaluation of the query by calling the ToList() method. (Keep
in mind that LINQ queries typically default to deferred loading, meaning that the query is not actually executed until
necessary. The ToList() method forces this very execution.) Enumerating this query brings all of the workers and all
of the serious accidents into the DbContext. The anonymous type didn't attach the accidents to the workers, but by
bringing them into the Context, Entity Framework will fix up the navigation properties, attaching each collection of
serious accidents to the appropriate worker. This process, commonly known as Entity Span , is a powerful yet subtle
side effect that happens behind the scenes to fix up relationships between entities as they are materialized into the
Entity Framework Context object.
We've turned off lazy loading so that only the accidents in our filter are loaded. (We'll discuss lazy loading further
Chapter 5.) With lazy loading on, all of the accidents would get loaded when we referenced each worker's accidents.
That would defeat the purpose of the filter.
Once we have the collection, we iterate through it, printing out each worker and their serious accidents. If a
worker didn't have any serious accidents, we print none to indicate their stellar safety record.
3-10. Applying a Left-Outer Join
Problem
You want to combine the properties of two entities using a left-outer join.
Solution
Suppose that you have a model like the one shown in Figure 3-11 .
Figure 3-11. Our model with a Product entity type and its related TopSelling entity type
The top-selling products have a related TopSelling entity. Of course, not all products are top sellers, and that's
why the relationship is one to zero or one. When a product is a top seller, the related TopSeller entity also contains the
customer rating for the product. You want to find and present all of the products and their related TopSeller entities
even if, in some cases, the product is not a top seller. In the case where a product does not have a related TopSelling
entity, we simply set to the rating to “0”. In database terms, this is called a left - outer join .
The code in Listing 3-22 demonstrates three slightly different approaches to this problem.
 
Search WWH ::




Custom Search