Most of the blood, toil, tears, and sweat that an ASP.NET developer experiences while building a web application is associated with writing the data access code. Microsoft introduced LINQ to SQL with .NET Framework 3.5 to reduce the work that a developer must perform when accessing a database. LINQ to SQL makes it much easier to write both simple and complex database-driven websites.
Writing data access code is difficult because it forces you to bridge two very different universes: the object universe and the relational universe. Your application logic (your C# or Visual Basic .NET code) inhabits the object universe, whose basic elements are classes and objects. The basic elements of the relational universe, on the other hand, are tables and rows.
You interact with the two universes by using two very different languages. The C# and Visual Basic .NET languages are used for working with objects, and the SQL language is designed for working with tables. If you want to communicate from the object universe to the relational universe, you’re forced to embed SQL strings in your C# or Visual Basic .NET code. These SQL strings are complete gibberish from the point of view of your C# or Visual Basic .NET application.
So how do you bridge this divide? LINQ to SQL bridges this divide by enabling a developer to pretend that the relational universe doesn’t exist. LINQ to SQL enables you to write all of your data access code by using C# or Visual Basic .NET. You let C# or Visual Basic .NET worry about how to translate your code into SQL in the background.
LINQ stands for Language Integrated Query. There are many different flavors of LINQ, such as the following:
- LINQ to Objects
- LINQ to Amazon
- LINQ to Entities
- LINQ over DataSets
- LINQ to XML
- LINQ to Flickr
- LINQ to LDAP
- LINQ to SQL
These various flavors of LINQ enable you to communicate with different data sources. For example, LINQ to Flickr enables you to perform queries against photos stored at the Flickr website. In this article, we’re concerned with LINQ to SQL, which is the flavor of LINQ that you’ll most likely use when communicating with a Microsoft SQL Server database. (Currently, LINQ to SQL works with Microsoft SQL Server only, and not with other databases such as Oracle or Access.)
To use LINQ to SQL, your web project must target .NET Framework 3.5. New websites created with Visual Studio 2008 target .NET Framework 3.5 by default, but you can target an existing application to use .NET Framework 3.5 within Visual Studio:
- Right-click the name of your project in the Solution Explorer window.
- Select Property Pages.
- Click Build.
- Select .NET Framework 3.5 from the drop-down Target Framework list (see Figure 1). Behind the scenes, performing this action modifies your web.config file so that it contains references to the right assemblies and uses the correct version of either the C# or Visual Basic .NET language.
Figure 1 Targeting a version of the .NET Framework.