Apps

Easily manipulate data with LINQ

.NET Language-Integrated Query (LINQ) simplifies data access by allowing you to interact with backend data sources using your familiar programming language as opposed to using SQL.

The buzz around .NET Language-Integrated Query (LINQ) is hard to ignore, especially since Microsoft is embracing it with the latest release of the .NET platform (beginning with C# 3.0 and Visual Basic 9.0) and Visual Studio 2008.

LINQ basically provides data access via the developer's language of choice without using SQL. Within the context of the .NET platform, LINQ is a set of extensions to the .NET Framework that encompass language-integrated query, set, and transform operations. Presently, C# and Visual Basic are extended with native language syntax via class libraries for working with data.

The key term in the LINQ name is integrated, as it applies to developers being able to interact with data sources via their own development language with C# and Visual Basic currently supported. The integration negates the need to be familiar with SQL, so you can use your favorite programming language when working with backend data.

LINQ was designed to work with any backend data source, and developers benefit from the many features of their IDE, such as Visual Studio 2008. This brings compile-time syntax checking, static typing, and code assist to code accessing external data -- features that are sorely missed when working with external tools like SQL Server Enterprise Manager.

Microsoft divides LINQ into three areas:

  • LINQ to Object: In-memory data is queried and manipulated.
  • LINQ to ADO.NET: This includes three variations: LINQ to SQL (working with relational data, with only SQL Server supported) provides an object relational mapping implementation, LINQ to DataSet (working with ADO.NET datasets), and LINQ to Entities (Microsoft ORM solution).
  • LINQ to XML: XML data sources are queried and manipulated.

These three areas of LINQ functionality are provided via various .NET class libraries.

Class libraries

LINQ functionality is provided via its own set of classes. The main LINQ namespace is System.Linq, which provides classes and interfaces that support queries that use LINQ. The following namespaces are also provided:

  • System.Linq.Expressions: Contains classes, interfaces, and enumerations that enable language-level code expressions to be represented as objects in the form of expression trees.
  • System.Data.Linq: Provides classes that facilitate LINQ to relational databases (LINQ to SQL).
  • System.Data.Linq.Mapping: Works with the System.Data.Linq namespace for working with relational database systems. It allows you to generate an object model that represents the structure and content of the data source.
  • System.Data.Linq.SqlClient: Contains provider classes for communicating with SQL Server and classes that contain query helper methods. This namespace is not intended for direct use in code.
  • System.Xml.Linq: Contains the classes for working with XML data sources (LINQ to XML). These classes allow you to do things such as load XML data from files or streams as well as query, validate, and manipulate XML trees. LINQ to XML is an in-memory XML programming interface that enables you to modify XML documents efficiently and easily.

A key facet of LINQ is that it provides complete query capabilities for any collection that implements IEnumerable or IQueryable. For in-memory objects to be enabled for LINQ, the object type should implement IEnumerable. For LINQ to XML and LINQ to ADO.NET, the underlying provider converts the target objects to IEnumerable-based collections.

IEnumerable

The fact that LINQ works with all collections that use the IEnumerable interface means the cost of entry to using LINQ is low because almost all .NET type containers support IEnumerable. The following C# sample provides a demonstration of using LINQ to work with an array of string values. An IEnumerable string is used to loop through all word values in the string array.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace LINQConsoleTest {

class Program {

static void Main(string[] args) {

string[] words = new string[3] { "TechRepublic.com", "CNET.com", "News.com"};

IEnumerable<string> wordQuery =

from word in words

select word;

foreach (string wrd in wordQuery) {

Console.WriteLine(wrd);

}}}}

While working with string data is good, SQL Server interaction will be more popular. Visual Studio 2008 includes a designer tool that provides a simple way to model and visualize a database as a LINQ to SQL data model. Database elements may be dragged and dropped into the designer environment; the result is a dbml file. The dbml file generates the class file for data operations like Create, read, update, and delete.

Once you drag and drop various database features to the designer, a name is assigned to the dbml file; this name is used to interact with its underlying data source. As an example, I created a connection to the employee table of the SQL Server Northwind database. The following C# code accesses the data source:

NorthwindDataContext db = new NorthwindDataContext();

var employers = from p in db.Employees

select p;

The equivalent Visual Basic code follows:

Dim db As New NorthwindDataContext
Dim employees = From p in db.Employees
select p;

I will provide more code details in next week's article.

Learning with LINQPad

When tackling a new technology, I prefer to jump in and get my hands dirty. With LINQ, you can do this by firing up Visual Studio 2008 and creating a new project that uses LINQ to connect to a data source. Also, a free tool called LINQPad provides an easy to use interface for working with LINQ functionality.

LINQPad is available as a free download. It is ready to use once the executable is downloaded. It comes with plenty of example code and allows you to easily work with LINQ by creating connections and interacting with the data source by dragging and dropping to a source pane or directly typing code.

Focus on the code

Microsoft has repeatedly vowed to reduce the workload of application developers by streamlining certain processes within its development platforms and tools. LINQ actually does simplify data access by allowing a developer to interact with backend data sources using their familiar programming language as opposed to using venerable SQL.

Have you had a chance to work with LINQ in the .NET Framework? Do you see advantages to negating the need of developers to learn and use SQL? Share your thoughts and experiences with the Visual Studio Developer community.

Tony Patton began his professional career as an application developer earning Java, VB, Lotus, and XML certifications to bolster his knowledge.

---------------------------------------------------------------------------------------

Get weekly .NET tips in your inbox TechRepublic's free Visual Studio Developer newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically subscribe today!

About

Tony Patton has worn many hats over his 15+ years in the IT industry while witnessing many technologies come and go. He currently focuses on .NET and Web Development while trying to grasp the many facets of supporting such technologies in a productio...

11 comments
bjries2
bjries2

I think that LINQ sounds very interesting, and has potential. Whether or not it may be considered successful depends on the following: 1. Usability; does it add much value? 2. Risk; is the value it adds worth the risk? 3. Adoption Rate; will it be embraced or shunned in .NET? As for #1, I see it more useful as LINQ to Objects and LINQ to XML. Many companies hosting databases already have application DAL/BLL that call Stored Procedures in the database. They really don't need (nor want) LINQ to ADO.NET, expecially for existing development. However, I do see a potential for LINQ to ADO.NET being useful in RapidApplicationDevelopment of reports and such, prototyping new apps with real data, debugging with "one time" queries, and cleaning up database data after unit-testing. As for #2, there is a very real risk, especially for new development, of LINQ to ADO.NET opening up a can-of-worms/maintenance-nightmare reminiscent of dynamic SQL. And, it seems that using it would open up many risks from NOT getting all of the advantages provided by using Stored Procedures. This contributes its FUD to #3. Also, I think many companies operate under the "version minus one" rule (my current company is just NOW migrating to 2.0!). So that LINQ (as a part of .NET 3/3.5) won't be widely adopted until .NET 4/4.5 or perhaps even 5!

hajray
hajray

Nice! I must add though that LINQ is offer with .NET Framework 3.5 and not 3.0.

jeremy.mitchell
jeremy.mitchell

Developers I know have enough trouble writing well performing SQL as it is without another layer that will produce even worse SQL. Where I see this having value is the ability to "join" data in memory from diverse data sources. Imaging filling on dataTable with information from an Oracle database, and another from DB2, and having the ability to relate the data together in memory without having to go through DTS, SSIS, or another data stagin middle layer that are often more trouble than they are worth. Just my 2 cents.

IT-b
IT-b

In my environment this can definitely come in handy with XML docs that we're parsing. Some are complicated and may or may not have data where we expect, so the ability to query for it might be nice. Stored procs still do the bulk of the database work, but this has a place.

jim
jim

I think for the new comer to databases, this is brilliant. For me, though, I prefer to stick to what I know in SQL.

Justin James
Justin James

LINq is going to take forever to hit mainstream. Remember, it's been pubic with .Net 3.0 for nearly a year now, and no one uses it yet... I like the LINQ idea "on paper". A number of concerns though: * Will this encourage the return of dynamic queries? I hope not. I hope people use LINQ in conjuction with stored procedures and let the DB folks write good SQL. Otherwise, well, back to the world of overloaded DB servers, tables that stay locked for too long, and so on. * On that note, no one seems to have evaluated where LINQ properly fits into the N-Tier architecture model. * The close ties to SQL Server worry me. Sure, it can handle ADO.Net as well... but how well will that work in reality? * It seems a bit... heavy handed... to use it for doing things like querying a generic. Sure, the one-line LINQ command is more elegant, but everyone know why you'd loop through a list searching for a value. * It completely breaks the OO model of VB.Net and C#. On the other hand... * I appreciate its unification of functionality, so we aren't using different techniques for different things. * I like the slow introduction of functional programming style things into the .Net universe. Now, to get a proper eval.() in the system, and I will be happy. :) * Depending on how good it is at querying the DB efficiently, we may finally see the removal of the DBA dependency. * It does make code more elegant, at the expense of breaking the OO model. Maybe the OO model is like the "Pirate Bylaws"... "they're more like guidelines, really..." J.Ja

Justin James
Justin James

I am fairly certain that C# 3.0 (with .Net 3.0) had LINQ, but VB.Net did not get LINQ until .Net 3.5. That's my recollection, at least. The problem was, .Net 3.0 shipped without any good tools (some really bad, and occassionally "beta" or "CTP" add ons to Visual Studio don't count...), so no one programmed against it, even though it was released nearly a year ago. J.Ja

Justin James
Justin James

I like the unified language and abstraction of the concept of data. Bringing some Lisp-ness to .Net is not a terribly bad plan. :) J.Ja

Tony Hopkinson
Tony Hopkinson

enough people developing database apps who don't know f'all about databases as it is.

Tony Hopkinson
Tony Hopkinson

It really comes into it's own productivity wise when say querying against two internal list classes. Or one and an xmldoc or dataset. You can go mental writing piles of similar code for that, or end up with some non-standard generic stuff that ends up with 20 parameters in the method call. Use it for what it's good at, I expect some juveniles will go mental with it, but that's not going to be for the first time with a 'new' feature.