Datasheet
Klein c01.tex V3 - 12/13/2007 1:48pm Page 9
Chapter 1: Project LINQ
To do this, a mapping to the database needs to be made, and that is accomplished by creating and
declaring two classes. Those classes map the relational objects into the object-oriented world. The first
class maps the actual database:
[Database(Name="AdventureWorks")]
public class AdventureWorks : DataContext
{
public AdventureWorks(string connection) : base(connection) {}
public Table
<
DirectoryInformation
>
DirectoryInformation;
}
The second class maps the table and columns of the table you want to access:
[Table(Name="DirectoryInformation")]
public class DirectoryInformation
{
[Column(DbType="varchar(50)")]
public string DirectoryName;
[Column(DbType = "varchar(255)")]
public string DirectoryDescription;
}
The class name maps to the table in the database you want to access, and the columns are mapped by
adding metadata to a couple of variables.
This example is just to whet your appetite. There’s not a lot of explanation here because there
are more than a handful of chapters that discuss object mapping and querying in much
greater detail.
Once the mapping is complete, the data can be queried. And not just queried, but queried using
strongly typed syntax.
The first line of the following code accesses the database as an object, creating a new instance of the class
previously defined, a strongly typed connection. Once you have the connection, you can access the table
and data in a strongly typed fashion, as shown in the second and third lines. Notice that the columns in
the table are accessed via dot notation directly in C#.
AdventureWorks db = new AdventureWorks("Integrated Security=sspi");
foreach (var item in db.DirectoryInformation)
listBox1.Items.Add(item.DirectoryName + " " +
item.DirectoryDescription);
Executing this code returns the data from the
DirectoryInformation
table and lists both the directory
name and description in a list box.
To make it more interesting, take the directory example from the beginning of the chapter and modify it
to join to this query. You’ll recall that the code in the earlier example simply queried the
DirectoryInfo
class to return the directories on your local C drive. Combining it with this query, you join the
Name
property of the
DirectoryInfo
class to the
DirectoryName
column from the
DirectoryInformation
9