本主題描述由 DataContext 所管理的識別快取中傳回物件的 LINQ to SQL 查詢類型。
在 LINQ to SQL 中,管理物件的其中一種方式 DataContext 是在執行查詢時記錄身分識別在身分識別快取中。 在某些情況下,LINQ to SQL 會在資料庫中執行查詢之前,嘗試從身分識別快取擷取物件。
一般而言,若要讓 LINQ to SQL 查詢從識別快取傳回對象,查詢必須以物件的主鍵為基礎,而且必須傳回單一物件。 特別是,查詢必須符合下列其中一種一般形式。
備註
預先編譯的查詢不會從識別快取傳回物件。 如需預先編譯查詢的詳細資訊,請參閱CompiledQuery和如何:儲存和重複使用查詢。
查詢必須符合以下一般格式之一,才能從身分識別快取擷取物件:
Table<TEntity>
.Function1(predicate)Table<TEntity>
.Function1(predicate).Function2()
在這些一般形式中, Function1、 Function2和 predicate 的定義如下。
Function1 可以是下列任一項:
Function2 可以是下列任一項:
predicate 必須是物件主鍵屬性設定為常數值的表達式。 如果物件有一個以上的屬性所定義的主鍵,則每個主鍵屬性都必須設定為常數值。 以下是表單 predicate 必須採用的範例:
c => c.PK == constant_valuec => c.PK1 == constant_value1 && c=> c.PK2 == constant_value2
範例
下列程式代碼提供從身分識別快取擷取物件之 LINQ to SQL 查詢類型的範例。
NorthwindDataContext context = new NorthwindDataContext();
// This query does not retrieve an object from
// the query cache because it is the first query.
// There are no objects in the cache.
var a = context.Customers.First();
Console.WriteLine($"First query gets customer {a.CustomerID}. ");
// This query returns an object from the query cache.
var b = context.Customers.Where(c => c.CustomerID == a.CustomerID);
foreach (var customer in b )
{
Console.WriteLine(customer.CustomerID);
}
// This query returns an object from the identity cache.
// Note that calling FirstOrDefault(), Single(), or SingleOrDefault()
// instead of First() will also return an object from the cache.
var x = context.Customers.
Where(c => c.CustomerID == a.CustomerID).
First();
Console.WriteLine(x.CustomerID);
// This query returns an object from the identity cache.
// Note that calling FirstOrDefault(), Single(), or SingleOrDefault()
// instead of First() (each with the same predicate) will also
// return an object from the cache.
var y = context.Customers.First(c => c.CustomerID == a.CustomerID);
Console.WriteLine(y.CustomerID);
Dim context As New NorthwindDataContext()
' This query does not retrieve an object from
' the query cache because it is the first query.
' There are no objects in the cache.
Dim a = context.Customers.First()
Console.WriteLine("First query gets customer {0}. ", a.CustomerID)
' This query returns an object from the query cache.
Dim b = context.Customers.Where(Function(c) c.CustomerID = a.CustomerID)
For Each customer In b
Console.WriteLine(customer.CustomerID)
Next
' This query returns an object from the identity cache.
' Note that calling FirstOrDefault(), Single(), or SingleOrDefault()
' instead of First() will also return an object from the cache.
Dim x = context.Customers. _
Where(Function(c) c.CustomerID = a.CustomerID). _
First()
Console.WriteLine(x.CustomerID)
' This query returns an object from the identity cache.
' Note that calling FirstOrDefault(), Single(), or SingleOrDefault()
' instead of First() (each with the same predicate) will also
' return an object from the cache.
Dim y = context.Customers.First(Function(c) c.CustomerID = a.CustomerID)
Console.WriteLine(y.CustomerID)