
206Microsoft 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
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