Deferred execution
IQueryable query = from c in ctx.Customers select c;
Such a query syntax does not cause the statement to execute immediately, it is just a description, corresponding to a SQL. Statements are executed only when they are needed, such as:
IQueryable query = from c in ctx.Customers select c;
foreach (Customer c in query)
Response.Write(c.CustomerID);
If you perform a two-foreach operation, the execution of the SQL statement will be captured two times:
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);
Corresponding 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]
For such a requirement, it is recommended that you first save the query results using the ToList () method, and then query the collection:
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);
The advantage of deferred execution is that we can stitch query syntax like concatenation SQL and then execute:
var query = from c in ctx.Customers select c;
var newquery = (from c in query select c).OrderBy(c => c.CustomerID);
DataLoadOptions
var products = from p in ctx.Products select p;
foreach (var p in products)
{
if (p.UnitPrice > 10)
ShowDetail(p.Order_Details);
}
private void ShowDetail(EntitySet<Order_Detail> orderdetails)
{}