Although using SQL-like syntax with your in-memory collections is the more interesting and unusual use of LINQ, it’s natural to use the SQL-like syntax with SQL databases. With LINQ, instead of using the
DataSet classes you learned about in Chapter 20, you can treat the tables in a SQL database as classes, and work with the data directly, as though the tables were objects created in your code.
Create a new console application to see how this works. To use the LINQ data features, you’ll need to add a reference to the
System.Data.Linq namespace, which is something you haven’t done before, but it’s simple. Right-click on the References folder of your project in the Solution Explorer. You’ll see the Add Reference dialog shown in Figure 21-1.
Figure 21-1. You’ll need to add a reference to the System.Data.Linq namespace before you can use LINQ with a SQL database.
Now that you have the reference, you need to add some
using statements to take advantage of them in your program:
using System.Data; using System.Data.Linq; using System.Data.Linq.Mapping;
As we mentioned earlier, when you’re using LINQ and SQL, you can treat the database tables as classes, and the columns as members. It just requires a bit of extra work on your part. You’ll retrieve some simple information from Northwind’s
Employees table in this example.
If you did the examples in Chapter 20 ...