Jaa


Using LINQ with ASP.NET

You can use Language-Integrated Query (LINQ) in Web pages to retrieve and modify data. LINQ applies the principles of object-oriented programming to relational data. It provides a unified programming model for querying data from different types of data sources, and extends data capabilities directly into the C# and Visual Basic languages. For more information, see Language-Integrated Query (LINQ).

You can use LINQ through the LinqDataSource control, through the ObjectDataSource control, or by creating LINQ queries.

When you use LINQ in a Web application, you might have to change the policy files for code-access security. These changes are described later in this topic.

LinqDataSource Control

The LinqDataSource control provides an easy way to connect to data from a database or to an in-memory data collection such as an array. You can declaratively write all the conditions that are required for typical scenarios such as retrieving, filtering, ordering, and grouping the data. The control dynamically creates the LINQ queries from the values that you provide declaratively.

When you retrieve data from a LINQ to SQL data context class, you can also configure a LinqDataSource control to handle update, insert, and delete operations. The control does this without requiring you to write the SQL commands to perform these tasks.

To display the data in a Web page, you bind a data-bound control to the LinqDataSource control. Examples of data-bound controls are the GridView or DetailsView controls.

The following example shows the markup for a LinqDataSource control that connects to the AdventureWorks database. It returns records from the Contact table that have a value in the EmailPromotion property equal to 1.

<asp:LinqDataSource 
    ContextTypeName="AdventureWorksDataContext" 
    TableName="Contacts" 
    Where="EmailPromotion=1"
    ID="LinqDataSource1" 
    runat="server">
</asp:LinqDataSource>

For more information, see LinqDataSource Web Server Control Overview.

ObjectDataSource Control

You use the ObjectDataSource control when you want to interact with the data in a more complex way than is possible with the LinqDataSource control. For example, you can create an update method that includes setting values in joined tables.

You can use the ObjectDataSource control with a LINQ to SQL class. To do so, you set the TypeName property to the name of the data-context class. You also set the SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod methods to the methods in the data-context class that perform the corresponding operations.

When you use deferred query execution with the ObjectDataSource control, you must create an event handler for the ObjectDisposing event in order to cancel disposing of the data-context class. This step is necessary because LINQ to SQL supports deferred execution, whereas the ObjectDataSource control tries to dispose the data context after the Select operation.

LINQ Queries

You can include LINQ queries in a Web page without using a data source control. You might use a LINQ query if you need to use a query operator that is not available in the LinqDataSource control. You might also use it if you want to display read-only data in a data-bound control without the processing that is required to create a data source control. For more information about LINQ operators, see Standard Query Operators Overview. For a list of the query operators that are available in the LinqDataSource control, see LinqDataSource Web Server Control Overview.

The following example shows how to include a LINQ query in a Web page. The example displays the results from the query in a GridView control.

[Visual Basic]

Protected Sub Page_Load(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim dataContext As AdventureWorksDataContext = _
            New AdventureWorksDataContext()
        Dim query = From contact In dataContext.Contacts _
          Where contact.EmailPromotion = 1 _
          Select contact

        GridView1.DataSource = query
        GridView1.DataBind()
    End If
End Sub

[C#]

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        AdventureWorksDataContext dataContext = 
            new AdventureWorksDataContext();

        var query = from contact in dataContext.Contacts
          where contact.EmailPromotion==1
          select contact;

        GridView1.DataSource = query;
        GridView1.DataBind();
    }
}

LINQ and Code-access Security

The following sections provide information about how to use LINQ under medium trust and under high trust.

Using LINQ with Medium Trust

To use LINQ in a Web application that is running under medium trust, you must include two elements in the policy file that is defined for Medium trust. By default, the web_mediumtrust.config file is the policy file for medium trust.

Within the SecurityClasses element, add a SecurityClass element with the following attributes:

<SecurityClass 
  Name="ReflectionPermission" 
  Description="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>

Within the PermissionSet element that has the Name attribute set to "ASP.Net", add an IPermission element that has the following attributes:

<IPermission
  class="ReflectionPermission"
  version="1"
  Flags="RestrictedMemberAccess"
/>

Note

The elements might have been added during the installation process.

Using LINQ with High Trust

To use LINQ in a Web application that is running under high trust, you must include one element in the policy file that is defined for High trust. By default, the web_hightrust.config file is the policy file for high trust. This file already includes an IPermission element within a PermissionsSet element that references the ReflectionPermission class. You must modify this element when you use LINQ.

Within the PermissionSet element that has the Name attribute set to "ASP.Net", find the IPermission element for ReflectionPermission and set it as follows:

<IPermission
  class="ReflectionPermission"
  version="1"
  Flags="ReflectionEmit, RestrictedMemberAccess"
/>

Note

This element might have been modified during the installation process.

See Also

Concepts

LinqDataSource Web Server Control Overview

Other Resources

Language-Integrated Query (LINQ)

LINQ to SQL

Object Relational Designer (O/R Designer)