Channels ▼

A Look at LINQ's LinqDataSource Control

In the .NET Framework 3.5, Language Integrated Query (LINQ) is a set of syntax extensions that add query capabilities to managed languages. Using LINQ, .NET applications can query and transform data using a SQL-like set of operators built into the language syntax and backed up by a new set of framework classes.

Depending on the data being queried, there are distinct flavors of LINQ. They are: Linq-to-SQL, Linq-to-Objects, Linq-to-XML, and Linq-to-DataSets. As the name might suggest, the Linq-to-SQL flavor will query and transform relational data stored in a SQL Server database. Note that this is a SQL Server-only feature and other databases are not supported. In general, Linq-to-SQL can be presented as a higher-level language to query and transform database tables and records. Compared to the SQL Server native T-SQL, Linq-to-SQL employs an object-based vision of the query, manages strongly typed data, and automatically resolves foreign keys and one-to-many relationships between tables. With Linq-to-SQL, you still go through ADO.NET objects and T-SQL strings; however, all of this is hidden from view and managed internally by the framework. From a developer's perspective, Linq-to-SQL is a kind of new query language that is easier to understand and code than T-SQL.

The LinqDataSource control makes LINQ capabilities available to ASP.NET developers through the popular data-source control architecture. Conceptually, the LinqDataSource control is similar to SqlDataSource in that both controls require that you specify the query directly in the markup of the page. It should be noted, though, that LinqDataSource doesn't require connection information. You bind the data source to a dynamically created class&#emdash;the data context class&#emdash;created with the help of a Visual Studio 2008 designer. Compared to ObjectDataSource, the LinqDataSource is simpler and quicker to use, as it doesn't require any manual coding of the business class; at the same time, the requested behavior is expressed through the LINQ language rather than with a method name. Here's how to use the LinqDataSource control:

<asp:LinqDataSource runat="server" ID="LinqDataSource1"
    TableName="Customers" />
<asp:DropDownList runat="server" ID="DropDownList1"
    DataSourceID="LinqDataSource1" />

The ContextTypeName property takes the name of the class generated by the Visual Studio 2008 O/R designer for your data model . The TableName takes the name of the table in that model. The declarative syntax of the LinqDataSource control lets you also specify criteria for displaying, filtering, and ordering data. If the target store is a SQL Server database, you can also configure the control to handle updates, inserts, and deletions of records. More importantly, you can do that without having to write the related SQL commands. Here's a more detailed example:

<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
     Select="new (CustomerID, CompanyName)"
     OrderBy="customerid, companyname desc"  
     Where="Country == @Country">
         <asp:ControlParameter Name="Country" 
              PropertyName="SelectedValue" />
<asp:DropDownList ID="CustomerList" runat="server"
     DataValueField="CompanyName" />  

The query returns a collection of dynamically created objects that include CustomerID and CompanyName properties. These objects are sorted by ID and company and are filtered by country. The name of the country is selected from a drop-down list named CountryList.

Not all the queries can be expressed as a plain string and assigned to the Select property of the LinqDataSource control. For example, the LINQ syntax fully supports JOINs and DISTINCT queries, but the parser of the string assigned to the Select property just doesn't recognize these operators. The workaround is quite simple and straightforward: you leave the Select property blank and add an event handler for the data source's Selecting event:

<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
     OnSelecting="LinqDataSource1_Selecting" />

In the body of the handler, you can use the full LINQ syntax to run the query without being limited by the string format and the capabilities of the embedded data source parser.

private NorthwindDataContext db;
protected void Page_Init(object sender, EventArgs e)
    db = new NorthwindDataContext();
protected void LinqDataSource1_Selecting(object sender,  LinqDataSourceSelectEventArgs e)
    var countries = (from c in db.Customers 
                     select new { c.Country }).Distinct();
    e.Result = countries;

The Result property on the LinqDataSourceSelectEventArgs class holds the list of objects that the data source will share with its bound controls.

The pattern behind LinqDataSource and SqlDataSource is nearly the same; the only difference is the language you use&#emdash;Linq-to-SQL in one case, and raw SQL in the other.

Another important difference is that SqlDataSource can accommodate any relational data source, whereas LinqDataSource is limited to SQL Server.

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.