Chapter 7: Working with Data | 207 |
query, a join query will combine two tables that have matching keys. Here’s an example of a join query that accomplishes the exact same task as the preceding select many query:
C#:
var myShop = new MyShopDataContext();
var customers =
from cust in myShop.Customers join ord in myShop.Orders
on cust.CustomerID equals ord.CustomerID select new
{
Name = cust.Name, Date = ord.OrderDate
};
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 Join ord In myShop.Orders
On cust.CustomerID Equals ord.CustomerID Select New With
{
.Name = cust.Name,
.Date = ord.OrderDate
}
For Each custOrd In customers
Console.WriteLine(
"Name: " & custOrd.Name &
"Date: " & custOrd.Date)
Next
The difference between this query and the select many is that there is a join clause instead of a second from. The join identifies a range variable, ord, and operates on the Orders property of the data context. You also must specify which keys of the table join, mentioning the parent first, cust.CustomerID, and then the child, ord.CustomerID. Remember to use the equals keyword because the equality operator will not work.