LINQ那些事兒(6)-對象生命週期管理

來源:互聯網
上載者:User

為了實現從”LINQ那些事”(1)-(5)中介紹的查詢特性,在從資料庫擷取資料至返回給使用者之間,除了O/R Mapping外,LINQ2SQL內建了對象標識緩衝和跟蹤等服務。本文無意討論這些服務實現的細節,但是稍微瞭解這些服務有助於我們更有效使用LINQ,並且為自己編寫LINQ擴充提供參考。

對象標識緩衝(identity caching)

讓我們來看看對象標識緩衝(identity caching)的第一個好處:

01 var context = GenerateContext();
02 context.Log = Console.Out;
03 var query1 =
04     (from c in context.Customers
05      select c).Take(100);
06
07 var watch = new Stopwatch();
08 watch.Start();
09 query1.ToList();
10 watch.Stop();
11 watch.ElapsedMilliseconds.Dump();
12
13 watch.Reset();
14 watch.Start();
15 query1.ToList();
16 watch.Stop();
17 watch.ElapsedMilliseconds.Dump();

查詢Northwnd的Customers表的100條記錄,兩處的query1.ToList()都執行了兩桶的資料庫查詢操作,但是兩處的時間有差別。看看輸出結果:

01 SELECT TOP (100) [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0]
02 .[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode],
03 [t0].[Country], [t0].[Phone], [t0].[Fax], [t0].[CustomerGuid]
04 FROM [dbo].[Customers] AS [t0]
05 -- Context: SqlProvider(Sql2008) Model: MappedMetaModel Build: 3.5.30729.1
06
07 1058
08 SELECT TOP (100) [t0].[CustomerID], [t0].[CompanyName], [t0].[ContactName], [t0]
09 .[ContactTitle], [t0].[Address], [t0].[City], [t0].[Region], [t0].[PostalCode],
10 [t0].[Country], [t0].[Phone], [t0].[Fax], [t0].[CustomerGuid]
11 FROM [dbo].[Customers] AS [t0]
12 -- Context: SqlProvider(Sql2008) Model: MappedMetaModel Build: 3.5.30729.1
13
14 3

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.