5. The LinqDataSource Class
In
the .NET Framework 3.5, Language Integrated Query (LINQ) is a set of
syntax extensions that add query capabilities to managed languages such
as C# and Visual Basic. With LINQ, .NET applications can query and
transform data using a SQL-like set of new operators natively embedded
in the language syntax and backed up by a new set of framework classes.
ASP.NET applications are no exception. ASP.NET 3.5 applications can
take advantage of a subset of the LINQ capabilities through a
made-to-measure data source control—the LinqDataSource control.
5.1 What’s Linq-to-SQL, Anyway?
LINQ
establishes the query as a first-class object in .NET 3.5 languages
such as C#. At the same time, LINQ builds up a new programming model to
query different types of data using a common set of operators such as from, select, and where.
What kind of data? There are four distinct flavors of LINQ, with a
fifth ready to join the group with the first service pack or upgrade to
the .NET Framework 3.5. They are: Linq-to-SQL, Linq-to-Objects,
Linq-to-XML, and Linq-to-DataSets, and to follow shortly,
Linq-to-Entities. As the name might suggest, Linq-to-SQL queries and
transforms relational data stored in a SQL Server database. Note that
this is a SQL Server-only feature and other databases are not
supported. Linq-to-Objects queries enumerable collections of .NET
objects, whereas Linq-to-XML allows you to explore and manipulate the
content of XML documents. Finally, Linq-to-DataSets adds a powerful
search engine on top of ADO.NET DataSet and DataTable objects.
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 relationships (that is, one-to-many relationships) between
tables. Unlike T-SQL, a Linq-to-SQL expression relies on language
native operators and doesn’t present itself as opaque text to be
processed through a connection, a command, or perhaps a transaction or
reader. 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.
5.2 The Goal of LinqDataSource
The LinqDataSource
control makes LINQ capabilities available to Web 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. Instead, you bind the data
source to a dynamically created class—the data context class—created
with the help of the Visual Studio 2008 Object/Relational (O/R)
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.
Note that this approach can be considered a weakness as well as a
strength of the control—it all depends on how much abstraction you need
in the design of the domain model and whether you’re looking for a
quick or a well-architected solution.
LinqDataSource
is not limited to querying and manipulating SQL Server data. You can
use it to access data defined in any referenced .NET class through a
public property. The following code snippet shows how to populate a
drop-down list with the contents of the AvailableGenres property of the BookLibrary class:
<asp:LinqDataSource runat="server" ID="LinqDataSource1"
ContextTypeName="BookLibrary"
TableName="AvailableGenres" />
<asp:DropDownList runat="server" ID="DropDownList1"
DataSourceID="LinqDataSource1" />
You can see what the BookLibrary class looks like in the following code snippet:
public class BookLibrary
{
string[] _availableGenres = { "Fiction", "Thriller", "Biography" };
public BookLibrary()
{
}
public string[] AvailableGenres
{
get { return _availableGenres; }
}
}
It goes without saying that the ContextTypeName and TableName
properties are perhaps more naturally assigned with the name of the
class generated by the Visual Studio 2008 O/R designer to represent the
current data model and the name of the table in that model,
respectively, that you want to work with.
The LinqDataSource
declarative syntax 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.
5.3 Programming Interface of the LinqDataSource Control
Table 10 lists the key properties defined on the LinqDataSource control. By using these properties, you can, as a developer, declaratively set attributes on the control tag in the .aspx source.
Table 10. Properties of the LinqDataSource Control
Property | Description |
---|
AutoGenerateOrderByClause | Boolean property, instructs the control to automatically generate the OrderBy clause of the Select statement to include all parameters listed in the OrderByParameters collection. It is set to false by default. |
AutoGenerateWhereClause | Boolean property, instructs the control to automatically generate the Where clause of the Select statement to include all parameters listed in the WhereParameters
collection. The automation, though, is limited to testing for equality
and requires that parameters in the list have names that exactly match
the column names in the table being searched. It is set to false by default. |
AutoPage | Boolean property, enables the user to page through the returned data. When you set this property to true, the data source lets data-bound controls know that paging is supported. In this case, say, a GridView control would subsequently set its AllowPaging property to true. This property is set to true by default. |
AutoSort | Boolean property, enables the user to sort the data dynamically. When you set this property to true, the data source lets data-bound controls know that sorting is supported. In this case, say, a GridView control would subsequently set its AllowSorting property to true. This property is set to true by default. |
ContextTypeName | Indicates the type of the class being used as the central repository of the data. If the LinqDataSource
control is bound to a SQL Server table, the type passed as an argument
here is the root object of the model created by the Visual Studio 2008
O/R designer. If the control is bound to an object, the property
indicates the class name. |
EnableDelete | Boolean property, lets data-bound controls know that the data source supports data deletion. This property is set to false by default. |
EnableInsert | Boolean property, lets data-bound controls know that the data source supports data insertion. This property is set to false by default. |
EnableUpdate | Boolean property, lets data-bound controls know that the data source supports data updates. This property is set to false by default. |
GroupBy | Indicates the value of the GroupBy LINQ operator used to group selected records by the specified set of columns. |
OrderBy | Indicates the value of the OrderBy LINQ operator used to sort returned records. To sort by multiple fields, separate column names with a comma. |
Select | Indicates the value of the Select projection LINQ operator. The content of this property defines the shape of the result set being returned. |
StoreOriginalValuesInViewState | Boolean
property, indicates whether the control should store in the view state
all the values that could be used to enforce conflict detection during
updates. This property is set to true by default. |
TableName | Indicates the name of the table to bind to. If the control is associated to an in-memory object, TableName then indicates the property on the object that contains the data to work on. |
Where | Indicates the value of the Where LINQ operator to filter the set of records being retrieved. |
The LinqDataSource control also features a few collection properties used to hold values for parametric clauses such as Where and OrderBy and parametric query and update operations. The list of collection properties includes DeleteParameters, GroupByParameters, InsertParameters, OrderByParameters, SelectParameters, UpdateParameters, and WhereParameters.
Along with TableName and ContextTypeName, the Select property is the key to the LinqDataSource control. Through the Select property, in fact, you specify the projection of data you want properly ordered, filtered, or grouped using the OrderBy, Where, and GroupBy clauses.