一步一步學Linq to sql(六):探究特性
[2] 一步一步學Linq to sql(六):探究特性
[3] 一步一步學Linq to sql(六):探究特性
[4] 一步一步學Linq to sql(六):探究特性
系列文章導航:
一步一步學Linq to sql(二):DataContext與實體
延遲執行
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); |