Partilhar via


Recuperando objetos do cache de identidade

Este tópico descreve os tipos de consultas LINQ to SQL que retornam um objeto do cache de identidade gerenciado pelo DataContext.

No LINQ to SQL, uma das maneiras pelas quais os objetos gerenciados é registrando identidades de objeto em um cache de identidade à medida que as DataContext consultas são executadas. Em alguns casos, o LINQ to SQL tentará recuperar um objeto do cache de identidade antes de executar uma consulta no banco de dados.

Em geral, para que uma consulta LINQ to SQL retorne um objeto do cache de identidade, a consulta deve ser baseada na chave primária de um objeto e deve retornar um único objeto. Em particular, a consulta deve estar em um dos formulários gerais mostrados abaixo.

Nota

As consultas pré-compiladas não retornarão objetos do cache de identidade. Para obter mais informações sobre consultas pré-compiladas, consulte CompiledQuery e Como armazenar e reutilizar consultas.

Uma consulta deve estar em um dos seguintes formulários gerais para recuperar um objeto do cache de identidade:

Nestas formas gerais, Function1, Function2, e predicate são definidas da seguinte forma.

Function1 pode ser qualquer um dos seguintes:

Function2 pode ser qualquer um dos seguintes:

predicate deve ser uma expressão na qual a propriedade de chave primária do objeto é definida como um valor constante. Se um objeto tiver uma chave primária definida por mais de uma propriedade, cada propriedade de chave primária deverá ser definida como um valor constante. Seguem-se exemplos da forma predicate que deve assumir:

  • c => c.PK == constant_value

  • c => c.PK1 == constant_value1 && c=> c.PK2 == constant_value2

Exemplo

O código a seguir fornece exemplos dos tipos de consultas LINQ to SQL que recuperam um objeto do cache de identidade.

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)

Consulte também