从标识缓存检索对象

本主题介绍 LINQ to SQL 查询的类型,这些查询从由 DataContext 管理的标识缓存中返回对象。

在 LINQ to SQL 中,管理对象的方式 DataContext 之一是在执行查询时记录标识缓存中的对象标识。 在某些情况下,LINQ to SQL 会在数据库中执行查询之前尝试从标识缓存中检索对象。

通常,要使 LINQ to SQL 查询从标识缓存返回对象,查询必须基于对象的主键,并且必须返回单个对象。 具体而言,查询必须符合下面所示的一般形式之一。

注释

预编译的查询不会从标识缓存返回对象。 有关预编译的查询的详细信息,请参阅 CompiledQuery 以及如何 :存储和重用查询

查询必须位于以下常规表单之一中,才能从标识缓存中检索对象:

在这些常规形式中,Function1Function2predicate的定义如下。

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 {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)

另请参阅