using linqdatasource control with linq to sql datacontext class
The LinqDataSource is a web server control used when developing ASP.NET applications. Using this control, we can query against the entity classes that represent the database and the tables. We can generate the entity classes through the Object Relational Designer - LINQ to SQL. An entity is a class that represent a database table. This control works with the LINQ to SQL DataContext class to retrieve and update the database. The LinqDataSource control is used in multi-tier applications. The LinqDataSource control present in the presentation layer interacts with the DataContext class which is in the data access layer.
We can create a LinqDataSource control using declarative markup. While declaring the LinqDataSource control in an ASP.Net page, we can set all the conditions to filter the data, order data and group the data. We can also configure the LinqDataSource control to handle insert, update and delete operations using properties without writing much sql code.
LinqDataSource control and DataContext class
The LinqDataSource control does not directly talk to the database but interacts through the DataContext class and entity classes which are generated when we create the LINQ to SQL class using The O/R Designer. The DataContext class represents the entire database and is used to interact with the sql server database.
Properties of LinqDataSource control
An important property of LinqDataSource control is the ContextTypeName property. Using the ContextTypeName property, we can specify the DataContext class.
Next important property is TableName. By setting the TableName property to the name of the class that represents the data table. For example, to connect to the Customer table in the SalesDB database, we set the ContextTypeName property to SalesDBDataContext � the name that we specify for the database object. We set the Table Name property to Customers. The following example is a declarative syntax for creating LinqDataSource control that connects to the SalesDBDataContext database.
< asp:LinqDataSource ID="LinqDataSource1" runat="server">
ContextTypeName=" SalesDBDataContext"
Select=�new (CustomerId, Name)�
TableName="Customers"
< /asp:LinqDataSource>
In the above program, we use the Select property to specify the particular columns to be retrieved in the query result. By default, all the columns are retrieved. In the above example, the CustomerId and Name columns of Customers table are displayed. The keyword new creates an anonymous type. The anonymous type is created automatically when we mention one or more columns in the Select property.