一步一步學Linq to sql(六):探究特性

作者: lovecherry  來源: 博客園  發布時間: 2008-09-26 23:06  閱讀: 9862 次  推薦: 0   原文鏈接   [收藏]  
 

系列文章導航:

一步一步學Linq to sql(一):預備知識

一步一步學Linq to sql(二):DataContext與實體

一步一步學Linq to sql(三):增刪改

一步一步學Linq to sql(四):查詢句法

一步一步學Linq to sql(五):存儲過程

一步一步學Linq to sql(六):探究特性

一步一步學Linq to sql(七):并發與事務

一步一步學Linq to sql(八):繼承與關系

一步一步學Linq to sql(九):其它補充

一步一步學Linq to sql(十):分層構架的例子

 

延遲執行

 

       IQueryable query = from c in ctx.Customers select c;

       這樣的查詢句法不會導致語句立即執行,它僅僅是一個描述,對應一個SQL。僅僅在需要使用的時候才會執行語句,比如:

 

        IQueryable query = from c in ctx.Customers select c;

        foreach (Customer c in query)

            Response.Write(c.CustomerID);

       如果你執行兩次foreach操作,將會捕獲到兩次SQL語句的執行:

 

        IQueryable query = from c in ctx.Customers select c;

        foreach (Customer c in query)

            Response.Write(c.CustomerID);

        foreach (Customer c in query)

            Response.Write(c.ContactName);

       對應SQL

 

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]

FROM [dbo].[Customers] AS [t0]

 

SELECT [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0].[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode], [t0].[Country], [t0].[Phone], [t0].[Fax]

FROM [dbo].[Customers] AS [t0]

       對于這樣的需求,建議你先使用ToList()等方法把查詢結果先進行保存,然后再對集合進行查詢:

 

        IEnumerable<Customer> customers = (from c in ctx.Customers select c).ToList();

        foreach (Customer c in customers)

            Response.Write(c.CustomerID);

        foreach (Customer c in customers)

            Response.Write(c.ContactName);

       延遲執行的優點在于我們可以像拼接SQL那樣拼接查詢句法,然后再執行:

 

        var query = from c in ctx.Customers select c;

        var newquery = (from c in query select c).OrderBy(c => c.CustomerID);

 

0
0
 
 
 
 

文章列表

全站熱搜
創作者介紹
創作者 大師兄 的頭像
大師兄

IT工程師數位筆記本

大師兄 發表在 痞客邦 留言(0) 人氣()