Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 7: Working with Data 205
A data context is the code that is generated by VS when you run the LINQ to SQL
item wizard. The Main method instantiates MyShopDataContext, which is the data
context. The name came from when the LINQ to SQL item wizard ran and your naming of
the *.dbml file.
LINQ to SQL queries are made with the data context, which contains a property that
holds a collection of the class type that the property is named after, myShop.Customers
and myShop.Orders in this case. The LINQ query in the Main method uses the myShop
data context instance to access the Customers collection in the from portion of the query.
NOTE
The LINQ to SQL provider uses pluralized data context properties. However, the
results are not perfect; for example, Deer becomes Deers, which is incorrect in English.
Additionally, pluralization is designed for English and will produce strange results in
languages other than English. If the pluralization generated by the LINQ of a class is
incorrect, you can either double-click the class name in the Designer or change the class
name via the Properties window.
This section introduced you to what goes into creating a LINQ to SQL query, but your
queries will likely need to work with multiple tables, as discussed in the next section.
Performing Queries on Multiple Tables
Until now, all queries have been from a single data source or table, like Customers in
Listing 7-3. Often, you need to combine the results from multiple tables, which is where
select many and join queries are useful. To demonstrate how joins work, we’ll define
a scenario where you need to know the dates of all orders made and the name of the
customer who made the order.
The select many lets you join tables based on associations in the LINQ to SQL
Designer. From the parent object, you navigate to the child object and are able to access
the properties of both parent and child. The following code shows how to perform a select
many query that gets data from the Customer and Order tables and repackages it into a
collection of data transfer objects:
C#:
var myShop = new MyShopDataContext();
var customers =
from cust in myShop.Customers
from ord in cust.Orders
select new
{
Name = cust.Name,
Date = ord.OrderDate
};