Chapter 7: Working with Data | 209 |
For Each custOrd In customers
Console.WriteLine(
"Name: " & custOrd.Name &
"Date: " & custOrd.Date)
Next
And the output is
Name: Meg Date: 1/1/1800 12:00:00 AM
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
For C#, the left outer join is accomplished the same way as a join except for two additional lines: the into clause and the second from clause. For VB, the left outer join is the same as the join except for three lines: the Into clause, the second From clause, and the Group keyword. The into clause specifies an identifier that is used by the from clause. In the from clause, DefaultIfEmpty will return the default value for the continuation variable type. In the preceding example, the continuation variable is customerOrders whose type is Order. Since LINQ to SQL types are classes and Order is a class from the Orders entity collection, the default value is null (Nothing in VB). Notice how I enhanced the projection with a ternary (immediate if in VB) operator to control what value is returned when the parent doesn’t have a child. When performing a left outer join, make sure you compare the value against its default value to determine if the parent doesn’t have a child and ensure that valid values are set. Not only does the preceding example demonstrate how to check for a default value, but it also shows that you can use expressions in your projections.
In addition to LINQ queries, you can call stored procedures. As you may recall from the previous discussion on working with the LINQ to SQL Designer, I described how to drag and drop a stored procedure from Server Explorer to the design surface. Adding the stored procedure to the design surface also added a method to the data context. Here’s how to use that method:
C#:
var myShop = new MyShopDataContext();
var customers = myShop.GetCustomers();
foreach (var cust in customers)
{
Console.WriteLine("Name: " + cust.Name);
}