Ескертпе
Бұл бетке кіру үшін қатынас шегін айқындау қажет. Жүйеге кіруді немесе каталогтарды өзгертуді байқап көруге болады.
Бұл бетке кіру үшін қатынас шегін айқындау қажет. Каталогтарды өзгертуді байқап көруге болады.
В этом разделе описываются типы запросов LINQ to SQL, возвращающие объект из кэша удостоверений, управляемого объектом DataContext.
В 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_valuec => 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)