Datasheet
Klein c01.tex V3 - 12/13/2007 1:48pm Page 15
Chapter 1: Project LINQ
Once this schema is defined, a query can be issued. This is where LINQ comes in. Using the standard
query operators, LINQ translates the query from its original query expression form into a SQL query for
execution on the server:
private void button5_Click(object sender, EventArgs e)
{
DataContext context = new DataContext("Initial
Catalog=AdventureWorks;Integrated
Security=sspi");
Table
<
Contact
>
contact = context.GetTable
<
Contact
>
();
var query =
from c in contact
select new { c.FirstName, c.LastName, c.EmailAddress} ;
foreach (var item in query)
listBox1.Items.Add(item.FirstName + " " + item.LastName + " " +
item.EmailAddress);
}
Following are partial results from the query:
gustavo Achong gustavo0@adventure-works.com
catherine0@adventure-works.com
kim2@adventure-works.com
humberto0@adventure-works.com
pilar1@adventure-works.com
frances0@adventure-works.com
margaret0@adventure-works.com
carla0@adventure-works.com
jay1@adventure-works.com
Obviously there is much more to LINQ to SQL, but the examples here illustrate what it can do and the
basic features and fundamental concepts of LINQ to SQL.
If you were to query this table via SQL Query AnalyzerorSQLServerManagementStudio,you’dknow
that the
Person.Contact
table in the AdventureWorks database is 28 rows shy of 20,000, so the preceding
list is only the first nine, but you get the idea. How would you filter this query to return only a specific
few rows?
Typically I like to wait until the third or fourth chapter to start handing out ‘‘homework assignments,’’
but with the background presented in this chapter you should be able to figure this out quite easily. The
Person.Contact
table has some additional columns that you can use to filter the results. For example, it
has a column named
Title
, which contains values such as ‘‘Mr.’’ and ‘‘Ms.’’ It also has a column named
EmailPromotion
,an
int
datatype with values of
0
through
2
.
Your exercise for this chapter is to filter the query on either the
Title
column or the
EmailPromotion
column, using a standard query operator, so that the results returned are much less that 20,000. FYI if
you are going to use the
Title
column: some of values of the column are null, so don’t query where
Title
is null.
15