Compartir vía


Recuperar objetos de la memoria caché de identidades

En este tema se describen los tipos de consultas LINQ to SQL que devuelven un objeto desde la memoria caché de identidad que está administrado por el DataContext.

En LINQ to SQL, una de las formas en que DataContext administra los objetos consiste en registrar identidades de objetos en una memoria caché de identidad a medida que se ejecutan consultas. En algunos casos, LINQ to SQL intentará recuperar un objeto desde la memoria caché de identidad antes de ejecutar una consulta en la base de datos.

En general, para que una consulta LINQ to SQL devuelva un objeto desde la memoria caché de identidad, la consulta debe estar basada en la clave principal de un objeto y debe devolver un único objeto. En particular, la consulta debe estar en uno de los formatos generales indicados a continuación.

Nota

Las consultas precompiladas no devolverán objetos desde la memoria caché de identidad. Para obtener más información sobre las consultas precompiladas, vea CompiledQuery y Cómo: Almacenar y reutilizar consultas.

Para recuperar un objeto de la memoria caché de identidad, una consulta debe tener uno de los formatos generales siguientes:

En estos formatos generales, Function1, Function2 y predicate se definen como se indica a continuación.

Function1 puede ser de cualquiera de las funciones siguientes:

Function2 puede ser de cualquiera de las funciones siguientes:

predicate debe ser una expresión en la que la propiedad de la clave principal del objeto está establecida en un valor constante. Si un objeto tiene una clave principal definida mediante más de una propiedad, cada una de estas propiedades debe estar establecida en un valor constante. A continuación, se ofrecen ejemplos del formato que debe tener predicate:

  • c => c.PK == constant_value

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

Ejemplo

El código siguiente proporciona ejemplos de los tipos de consultas LINQ to SQL que recuperan un objeto desde la memoria caché de identidad.

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 también