O'Reilly logo

Learning C# 3.0 by Brian MacDonald, Jesse Liberty

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required