Microsoft 9GD00001 Computer Accessories User Manual


 
206 Microsoft Visual Studio 2010: A Beginner’s Guide
foreach (var custOrd in customers)
{
Console.WriteLine(
" Name: " + custOrd.Name +
" Date: " + custOrd.Date);
}
VB:
Dim myShop As New MyShopDataContext
Dim customers =
From cust In myShop.Customers
From ord In cust.Orders
Select New With
{
.Name = cust.Name,
.Date = ord.OrderDate
}
For Each custOrd In customers
Console.WriteLine(
" Name: " & custOrd.Name &
" Date: " & custOrd.Date)
Next
And here’s the output:
Name: Joe Date: 1/5/2010 12:00:00 AM
Name: May Date: 10/5/2010 12:00:00 AM
Name: May Date: 10/23/2010 12:00:00 AM
Imagine that the preceding code is sitting in the Main method, like what you saw in
Listing 7-3. The different part of this query that makes it a select many type of query is
the second from clause. Consider the parent/child relationship between Customer and
Order, which is represented by cust and ord in this query. The second from clause uses
the cust instance to specify the orders to query, which will be all orders belonging to each
customer. The ord instance will hold each order belonging to its associated cust. To make
this data useful, the projection is on an anonymous type that pulls together the name of the
customer and the date of that customer’s order.
In the database, I created two orders for May, one order for Joe, and zero orders for
Meg. Since there wasn’t an order for Meg, you don’t see any items from Meg in the
output. Later, I’ll show you how to add a parent record, even when that parent record has
no child records.
The select many query is fine for simple queries but becomes harder to use in more
complex queries. In this case, a join query emerges as an easier option. Like a select many