LINQ編程模型詳細(xì)分析
在向大家詳細(xì)介紹LINQ編程模型之前,首先讓大家了解下什么是LINQ?,然后全面介紹LINQ編程模型。
什么是LINQ?
LINQ是Language Integrated Query的縮寫,翻譯成漢語就是語言集成查詢。搜索一下網(wǎng)絡(luò),可以發(fā)現(xiàn)很多關(guān)于LINQ的描述:
1,LINQ是所有類型數(shù)據(jù)的統(tǒng)一編程模型,它可以讓你使用一致的模型查詢和使用數(shù)據(jù),而不用關(guān)心數(shù)據(jù)源是什么。
2,LINQ是一種將SQL查詢嵌入到代碼中的另一種工具
3,LINQ是另外一種數(shù)據(jù)抽象層。
以上這些描述在某種程度上都是正確的,但每種描述都僅僅集中在一個方面。LINQ能夠做的事情遠(yuǎn)遠(yuǎn)比嵌入的SQL查詢要多很多,它也比“統(tǒng)一的編程模型”更容易使用,同時也遠(yuǎn)不止是數(shù)據(jù)模型的另外一套規(guī)則。
LINQ是一套簡化和統(tǒng)一數(shù)據(jù)訪問的實現(xiàn)方法。LINQ并不是要求你使用一種特定的架構(gòu),它使一些現(xiàn)有訪問數(shù)據(jù)架構(gòu)的實現(xiàn)更加便利。和使用其他工具一樣,LINQ也存在好和壞兩個方面。要從LINQ中得到最好的東西,就需要對它有所精通。
LINQ編程模型,將查詢作為一流的概念引入到Micosoft .NET語言中。當(dāng)然,這需要編程語言和框架(.NET Framework 3.5)的支持。
下面的代碼將在頁面上的GridView2中顯示Country為USA客戶名稱:
- NorthWindDataContext NorthWind = new NorthWindDataContext();
- var query = from c in NorthWind.Customers where c.Country == "USA" select c.CompanyName;
- GridView2.DataSource = query;
- GridView2.DataBind();
當(dāng)然,也可以在ASPX頁面里進(jìn)行設(shè)置:
- <%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>LINQ 學(xué)習(xí)</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="GridView1" runat="server"
DataSourceID="LinqDataSource1" AllowSorting="True"- AutoGenerateColumns="False">
- <Columns>
- <asp:BoundField DataField="CompanyName"
HeaderText="CompanyName" ReadOnly="True"- SortExpression="CompanyName" />
- <asp:BoundField DataField="ContactName"
HeaderText="ContactName" ReadOnly="True"- SortExpression="ContactName" />
- <asp:BoundField DataField="Country"
HeaderText="Country" ReadOnly="True" SortExpression="Country" />- </Columns>
- </asp:GridView>
- </div>
- <asp:LinqDataSource ID="LinqDataSource1"
runat="server" ContextTypeName="NorthWindDataContext"- Select="new (CompanyName, ContactName, Country)"
TableName="Customers" Where="Country == @Country">- <WhereParameters>
- <asp:Parameter DefaultValue="USA" Name="Country" Type="String" />
- </WhereParameters>
- </asp:LinqDataSource>
- <hr />
- <asp:GridView ID="GridView2" runat="server">
- </asp:GridView>
- </form>
- </body>
- </html>
【編輯推薦】