Larry O'Brien: LINQ Clicks
November 15, 2007 —
(Page 1 of 2)
The forthcoming releases of Microsofts major .NET languages, C# and Visual Basic, support Language Integrated Query (LINQ), an important innovation that is garnering essentially unqualified raves and already being extended in fascinating new ways.
Its been a long while since Ive discussed LINQ in this column and, as the facility is on the verge of widespread release, its well worth revisiting.
LINQ is a language feature that allows relational operators to be applied to objects. The obvious use for this is to replace embedded SQL, which is enabled by LINQ to SQL (often called DLinq). The advantage of native-language data manipulation is probably obvious, but just to spell out the biggest wins, the manual mapping of table names, column names and SQL types to runtime classes, fields and CLR types has always been extremely tedious and error-prone, and its an uncommon application that maintains its plain-text SQL queries in an easily evolvable store uncoupled from application code.
The magic of Dlinq requires an explicit mapping, a subtype of DataContext, between the SQL and object world views. Generally, this mapping can be created by dropping a SQL model onto a design surface and clicking OK a few times. Customization is very easy, thoughsomething that I appreciated after having some experience trying to apply Rubys ActiveRecord library to a legacy database. It should be said that there are many complexities to object-relational mapping, and I will be shocked if the next year does not bring at least one high-volume complaint about the characteristics of the default mapping.
Once you have a DataContext subtype, you can begin querying the data. Although the syntax of LINQ is determined by the language designer, not the runtime, in the case of both C# and VB youll see keywords such as select, from, and where that will be familiar to any SQL user.
Just the presence of strongly typed entity classes would be nice enough (hello, IntelliSense!), but LINQ additionally supports all the common operators of the relational algebra. This means that, just as a SQL query can result in a table with columns that are mixed-and-matched from the source table, so too can you create objects that are mixed-and-matched from their sources! The implications of that are fairly extensive and lead to concepts such as anonymous types and closures that may be unfamiliar to some, but which are pretty easy to understand in their workaday usage. Dont be dismayed by the sudden explosion in Internet material on functional programming and extension methods; as interesting as that speculation is, its not part of the core learning process.