RVN012 - Batch independent session operations using the lazy API
-
RVN012 reports independent
Loadcalls and materializing queries on the same session that can be sent to the server in a single request using the lazy API. -
Default severity: Info
Automated code fix: Yes -
In this article:
Description
Separate requests:
Each eager Load call or materializing query (ToList, ToArray) can send a separate request to the server.
Batching requires independent operations:
To combine these operations into one request, each operation's inputs (the document ID or IDs for a load, or the query definition)
must be available without waiting for another operation's result.
Operations that meet this condition are called independent.
Batching with the lazy API:
When a method performs two or more independent operations on the same session,
they can be registered as lazy operations and sent together in a single multi-get request, reducing network round-trips and latency.
Trigger condition
When is RVN012 reported?
RVN012 reports two or more independent loads or materializing queries that meet all of the following conditions:
- Use the same session, referenced through a local variable, parameter, or field.
- Occur in the same block and branch within the same method.
See Operations in separate blocks, branches, or nested functions. - Use one of the forms listed under Supported operations.
- Are not separated by a call that prevents grouping, such as
SaveChanges().
See Calls that separate operations.
The operations must also be distinct. Repeated loads with the same T and either the same constant ID
or the same unmodified local variable or parameter as the ID or IDs argument count as one operation.
RVN012 is reported on the method name of each qualifying operation.
Supported operations
RVN012 checks the following operations in both sync and async sessions:
-
Loads:
session.Load<T>(id),session.Load<T>(ids),session.LoadAsync<T>(id), andsession.LoadAsync<T>(ids). Only single-argument overloads qualify.
Here,idis a single document ID, andidsis anIEnumerable<string>of document IDs.Requirements for load arguments
The ID or IDs argument must be a literal or a simple identifier referring to one of the following:
- A parameter, field, or property.
- A local variable initialized from a literal or another simple identifier.
For example,
CustomerIdqualifies, whilethis.CustomerIdis treated as dependent.The argument must not hold a value taken from another load or query result in the method.
-
Queries:
ToList(),ToArray(),ToListAsync(), andToArrayAsync(), called without arguments on a query that starts fromsession.Query<T>(). The query can be stored in a local variable, and its chain can include standardSystem.Linqoperators such asWhere.
The query, including its predicates, must not use a value taken from another load or query result in the method.
When is RVN012 not reported?
First,FirstOrDefault,Single,SingleOrDefault,Any,Count,LongCount, and their async forms.
RVN012 checks only the query materializers listed under Supported operations.Load<T>(id, includes),LoadAsync<T>(id, token),
and query materializers called with an argument, such asToListAsync(token).- A load whose ID or IDs argument is any other expression, such as string concatenation or interpolation,
a member access likeorder.CustomerId, a method call, or an inline array such asnew[] { "orders/1-A" }.
These are treated as dependent. A local variable initialized directly withnew[] { ... }is also excluded. - Queries via
session.Advanced.DocumentQuery<T>()orsession.Advanced.RawQuery<T>(). - Operations on a session reached through a property or a method call, such as
Session.Load<T>(id)orGetSession().Load<T>(id).
Only a local variable, a parameter, or a field is treated as a single session instance.
Operations in separate blocks, branches, or nested functions
- Operations in separate
if/elsebranches,try/catchblocks, loop bodies,switchsections, orswitchexpression arms are not grouped. - Each arm of
?:, the right-hand side of??,??=,&&, and||, and the part after?.are also treated as separate branches. - Operations inside lambdas and anonymous methods are not reported.
- Operations inside local functions are excluded from the enclosing method's group.
Calls that separate operations
Operations separated by certain session calls are not grouped together by RVN012.
These intervening calls are called session barriers.
Each side of a barrier is checked separately.
RVN012 can still report a group if either side contains at least two qualifying operations.
For example:
var order = session.Load<Order>("orders/1-A");
session.SaveChanges();
var product = session.Load<Product>("products/1-A");
The following are barriers: Calls on the session or directly on Calls on objects reached through A direct call on another session splits only that session's operations.SaveChanges() separates these loads into two groups, each containing only one operation.
RVN012 therefore does not report a diagnostic for this example.Which calls are session barriers?
session.Advanced, except for the method names listed below.
Examples include Store, Delete, SaveChanges, Advanced.Evict, Advanced.Clear,
Advanced.Refresh, Advanced.Exists, CountersFor, and TimeSeriesFor.session.Advanced with the following method names are not barriers,
unless the session is passed as an argument:
Load, LoadAsync, Query, and Include.DocumentQuery, AsyncDocumentQuery, RawQuery, and AsyncRawQuery.IsLoaded, HasChanged, WhatChanged, and WhatChangedFor.GetDocumentId, GetMetadataFor, GetChangeVectorFor, GetCountersFor, GetTimeSeriesFor,
GetLastModifiedFor, GetTrackedEntities, and GetCurrentSessionNode.session.Advanced, such as Advanced.Lazily, Advanced.Eagerly,
Advanced.Attachments, or Advanced.Revisions, are not barriers unless the session is passed as an argument.
A lambda or a local function call containing a barrier splits the operations of all sessions.
How to resolve
-
Register the operations with
session.Advanced.Lazily.Load<T>(id)andquery.Lazily(),
or withsession.Advanced.Lazily.LoadAsync<T>(id)andquery.LazilyAsync()in an async session,
then read the values. -
Reading the first
.Value(awaiting it in an async session) sends all pending lazy operations to the server in a single request. -
Calling
session.Advanced.Eagerly.ExecuteAllPendingLazyOperations()
(orExecuteAllPendingLazyOperationsAsync()) before reading the values is optional. -
The automated code fix converts eligible loads and queries to lazy operations and adds code to read their values.
See Automated code fix.
Before (triggers RVN012)
// Triggers RVN012: two independent loads that may send two separate requests.
var order = session.Load<Order>("orders/1-A");
var product = session.Load<Product>("products/1-A");
After (correct)
var lazyOrder = session.Advanced.Lazily.Load<Order>("orders/1-A");
var lazyProduct = session.Advanced.Lazily.Load<Product>("products/1-A");
// Reading the first value sends both loads in a single request.
var order = lazyOrder.Value;
var product = lazyProduct.Value;
Async session
var lazyOrder = asyncSession.Advanced.Lazily.LoadAsync<Order>("orders/1-A");
var lazyProduct = asyncSession.Advanced.Lazily.LoadAsync<Product>("products/1-A");
// Awaiting the first value sends both loads in a single request.
var order = await lazyOrder.Value;
var product = await lazyProduct.Value;
Mixing loads and queries
var lazyCompany = session.Advanced.Lazily.Load<Company>("companies/1-A");
var lazyOrders = session.Query<Order>()
.Where(x => x.Company == "companies/1-A")
.Take(50)
.Lazily();
// Reading the first value sends the load and the query in a single request.
var company = lazyCompany.Value;
var orders = lazyOrders.Value.ToList();
Automated code fix
Which operations does the code fix rewrite?
When you apply the code fix to a reported operation, it selects a group of consecutive declarations around that operation in the same block.
Each declaration must declare one variable whose entire initializer is a single-argument load
or a supported query materializer called without arguments, such as
var x = session.Load<T>(id);, var x = await session.LoadAsync<T>(id);, or var xs = session.Query<T>().ToList();.
The selection extends both before and after the reported declaration.
It stops at a statement that is not such a declaration, that contains a session barrier, or whose load or query fails
the independence checks described under Supported operations.
Reported operations outside this group, such as operations after a SaveChanges() call, are not changed.
Apply the code fix to them separately.
For example, the code fix batches order and employee and leaves company unchanged after them:
var order = session.Load<Order>(orderId); // Reported
var employee = session.Load<Employee>(employeeId); // Reported
var company = session.Load<Company>(order.Company); // Not reported; ends the selection
How does the code fix rewrite your code?
The code fix:
- Renames each selected variable, for example from
ordertolazyOrder,
and replaces its initializer withsession.Advanced.Lazily.Load<T>(id)/LoadAsync<T>(id),
or withquery.Lazily()/query.LazilyAsync(). - After all lazy registrations, re-declares each original variable with its original type, reading the lazy value:
lazyX.Value,await lazyX.Value,lazyXs.Value.ToList(), or(await lazyXs.Value).ToList().
Array queries useToArray()instead ofToList(). - Adds
using Raven.Client.Documents;when a query was rewritten and the namespace is not already in scope.
Reading the first value (awaiting it for async operations) sends the batch.
The code fix does not add an ExecuteAllPendingLazyOperations call.
Applied to the Before example, it produces code equivalent to the After example.
When is the code fix not offered?
RVN012 can report operations even when the automated code fix is unavailable.
In the following cases, change the code manually:
- The reported operation is not the whole initializer of a declaration that declares one variable,
for example when it is assigned to an existing variable, returned, or passed as an argument. - The selected group has fewer than two operations.
- The group mixes sync and async operations, or uses more than one session.
- An async operation in the group is not directly awaited.
Limitations
-
Only operations in the same method body are grouped.
Operations split across helper methods are not detected. -
Dependency tracking does not follow the order of statements.
Once a local variable, parameter, field, or property receives a value taken from a load or query result anywhere in the method, it is treated as dependent throughout, so a load or query that uses it is not reported, even after it is reassigned to an independent value.
Related C# analyzers
- RVN013
Fires when a query result is not bounded byTake(), including queries registered withLazily()orLazilyAsync(),
such as those produced by the RVN012 code fix.