Channels ▼
RSS

.NET

ASP.NET and LINQ


It's hard to imagine a piece of software that never needs to query for data. When this happens, chances are that the data to query comes from a relational database. Like it or not, the old faithful Structured Query Language (SQL) invented in the early 70s at IBM is still our main source of inspiration when it comes to setting up a query against some data. Whenever we developers think of a query we automatically put it down as a SELECT FROM some sort of storage medium. In spite of the high demand for queries, programming languages never added query operators to their baggage; that is, until the newest Visual Basic .NET and C# compilers in the .NET Framework 3.5 shipped with the Language Integrated Query (LINQ) facilities. (The .NET Framework 3.5 is currently in Beta 2, but it's scheduled for release later this year).

Available in Visual Studio 2008, the new VB.NET and C# compilers make querying a first-class concept and supply ad hoc operators. It is interesting to point out that none of the core data classes in the .NET Framework (namely, system.data) has been touched to support the new query model. New classes and tools have been introduced in the .NET Framework, but they are insulated in new assemblies. Operators in the languages automatically bind to these low-level classes and make rich data queries a reality in the .NET Framework 3.5.

LINQ defines a set of query operators that allow code to filter, enumerate, and select data from a variety of data sources using the same syntax—to a large extent reminiscent of SQL. LINQ-enabled data sources currently include arrays, collections, ADO.NET DataSets, XML, and result sets obtained from relational databases. The model is extensible to the point that third-party vendors can create and sell their own LINQ engine to query inside of their own data model using the standard syntax and set of operators.

The general-purpose query engine of LINQ is specialized in a library specific of a given data source. So you have LINQ-to-SQL to query relational data, LINQ-to-XML to query XML documents, and so forth. All these engines belong to the .NET Framework and are backed up by language compilers. Because ASP.NET is just a development platform built on top of the .NET Framework, there's no reason why you can't query data in a Web context using any of the LINQ engines. The following code, therefore, is perfectly legal and works successfully as long as you run it from within an ASP.NET 3.5 project.


protected void Button1_Click(object sender, EventArgs e)
{
   // Getting data
   var data =
        from c in context.Customers
        where c.Country == "USA"
        select c;

   // Simple and direct binding
   GridView1.DataSource = data;
   GridView1.DataBind();
}

As you can see, the code is bound to the Click event of a Web button. It selects all the customers from the United States that can be located in the configured context (in the end, a connection string to a relational SQL Server database). Where are the new LINQ operators and syntax elements? The var element defines a piece of data whose type will be inferred at run time. Operators like from, where, and select—just like the similar SQL operators—define the returned result set of the query and its source.

Using LINQ syntax from within ASP.NET 3.5 page is definitely possible. Can we ask for more? In ASP.NET applications, you can use any flavors of LINQ in a variety of ways, mostly depending on your vision of the overall application's architecture. For example, you can use any LINQ syntax to query data directly in the UI layer of the pages. More likely, instead, you might want to use any LINQ in the Data Access Layer of a multi-tier system.


<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
     ContextTypeName="NorthwindDataContext" 
     TableName="Customers"
     Select="new (CustomerID, CompanyName, Country)"  
     Where="Country == @Country">
  <whereparameters>
     <asp:parameter Name="Country" Type="String" DefaultValue="USA" />
  </whereparameters>
</asp:LinqDataSource>

Finally, if you love pages with a close-to-zero amount of code, you can use the new LinqDataSource control to specify LINQ commands and bind results to ASP.NET controls according to the popular data source model.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video