Using LINQ with SQL

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 DataAdapter and 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.

You’ll need to add a reference to the System.Data.Linq namespace before you can use LINQ with a SQL database.

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.

Tip

If you did the examples in Chapter 20 ...

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.