LINQ 101 - Which Flavor?

LINQ has permeated the .NET world. How to use LINQ, the different types of LINQ, how LINQ’s query expressions break down into C# 3’s newest features, and so on. LINQ has even had some of its old names tossed aside in the process. For example, LINQ to SQL was formerly known as DLinq. For the most part I have quietly indulged in all things LINQ and avoided writing too much on the specific syntaxes of how/when to use it (or not to use it). But now that LINQ, ADO.NET vNext and Orcas are getting close to the point where significant changes are less likely, I thought I might answer some fundamental questions about the flavors of LINQ in a brief post.

 

Once people get into LINQ, the biggest confusion I get email on regarding LINQ is how to choose between LINQ to SQL (formerly DLinq) and LINQ to Entities. In short, LINQ to SQL allows you to query an object model that maps directly to your relational database schema. The mapping is 1 class object to 1 db schema object. This is a simpler form than the abstraction model of LINQ to Entities …. which allows you to query an object that can be translated into 1 or more tables (for example) in your database. With LINQ to entities, the object model that you query with LINQ can be very different than the database schema.

 

Here is a quick primer on some of the flavors of LINQ:

 

LINQ to SQL

(Formerly known as DLinq)

Objects get mapped directly to database tables. Basically lets  you perform LINQ queries directly on the database schema via objects.

If your existing architecture has objects that map 1 to 1 with your database schema, then LINQ to SQL would be the closest match.

Add a *.dlinq file and drag tables/procs/table value functions/views from Server Explorer to the designer. Can also use SQLMetal to generate classes.

LINQ to Entities

Provides a layer of abstraction from the relational database structure. (aka you can combine tables into a single class, or you can use inheritance). Objects can represent the relational tables in OOP

There is a conceptual model, a database schema, and then there is the mapping between the 2. The conceptual objects are mapped through an XML mapping on to the database schema.

Add a .edm model file and create entities and their associations in the designer. Can also generate an EDM model (with the .ssdl, .csdl, .msl and .cs files).

LINQ to XML

(Also known as XLinq)

LINQ over XML structures

LINQ to DataSets

Using LINQ with ADO.NET DataSet and DataTable objects.

LINQ to Objects

Using LINQ  with collections implementing IEnumerable<T>