To give a simple taste of using LINQ, we
will build a simple Product Listing page that lists products like
the image below.
Figure 9
To implement this, I will
add a templated ASP.NET DataList control to the .aspx page using the markup
below to define the UI for each product in our list.
Listing 1
<span lang=EN><asp:DataList ID="DataList1" RepeatColumns="2" runat="server">
<ItemTemplate>
<div class="productimage">
<img src="images/productimage.gif" />
</div>
<div class="productdetails">
<div class="ProductListHead">
<%#Eval("ProductName")%>
</div>
<span class="ProductListItem">
<strong>Price:</strong>
<%# Eval("UnitPrice", "{0:c}") %>
</span>
</div>
</ItemTemplate>
</asp:DataList> </span>
I can then use the below code-behind class to
execute a LINQ query against the class library data model we defined in our
class library previously to retrieve all of the products in the database
supplier by the "Exotic Liquids" supplier and sorted by the product
name.
Listing 2
<span lang=EN>using System;
using System.Web;
using System.Query;
using LINQClassLibrary;
public partial class HelloWorld : System.Web.UI.Page { </span>
<span lang=EN>
protected void Page_Load() {</span>
<span lang=EN>
NorthwindDataContext db = new NorthwindDataContext();
DataList1.DataSource = from p in db.Products
where p.Supplier.CompanyName == "Exotic Liquids"
orderby p.ProductName
select p;
DataList1.DataBind();
}
} </span>
Notice how the LINQ query is strongly-typed
and can incorporate the Product/Supplier entity association we setup earlier
(for example, note how the where statement is able to
search by the product's Supplier.CompanyName property which is stored in the
Suppliers table and is linked to the
Products table via a primary key/foreign key relationship).
This strong typing model means I get
compile-time checking of my LINQ queries today and will get full intellisense
support with the new release of Visual Studio. No more runtime SQL syntax
errors!
And that is it. No additional code
required.