Поделиться через


Извлечение объектов из кэша идентификации

В этом разделе описаны типы запросов LINQ to SQL, которые возвращают объект из кэша идентификаторов, управляемого DataContext.

В LINQ to SQL в качестве одного из способов управления объектами DataContext регистрируют идентификаторы объектов в кэше идентификаторов во время выполнения запросов. В некоторых случаях LINQ to SQL пытается получить объект из кэша идентификаторов перед выполнением запроса в базе данных.

Обычно, чтобы запрос LINQ to SQL мог вернуть объект из кэша идентификаторов, запрос должен быть основан на первичном ключе объекта и должен возвращать одиночный объект. В частности, запрос должен иметь одну из общих форм, представленных далее.

Примечание.

Предварительно скомпилированные запросы не возвращают объекты из кэша идентификаторов. Дополнительные сведения о предварительно скомпилированных запросах см. в разделе CompiledQuery " Практическое руководство. Хранение и повторное использование запросов".

Чтобы получить объект из кэша идентификаторов, запрос должен иметь одну из следующих общих форм.

В этих общих формах параметры Function1, Function2 и predicate определяются следующим образом.

Параметр Function1 может иметь любое из следующих значений.

Параметр Function2 может иметь любое из следующих значений.

Параметр predicate должен быть выражением, в котором свойство первичного ключа объекта устанавливается в постоянное значение. Если первичный ключ определен в нескольких свойствах объекта, то в каждом свойстве должно быть задано постоянное значение. Далее представлены примеры формы, которую должен принимать параметр predicate.

  • c => c.PK == constant_value

  • c => 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 {0}. ", 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)

См. также