从实体缓存检索对象
本主题介绍从 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_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)