Session queried within an iteration
Marten1000 Warning
Cause
Data is queried within an iteration (while
, do-while
, foreach
, for
) through IQuerySession
(Load
, LoadAsync
, LoadMany
, LoadManyAsync
, Query
, QueryAsync
)
or IBatchedQuery
(Load
, LoadMany
, Query
).
Reason for rule
Queries within an iteration can indicate Select N+1 issues (see, What is N+1 SELECT query issue?). This rule aids in locating such sites, supporting manual code review of violations.
How to fix violations
To fix a violation of this rule, joins can be used to load related data. Otherwise remodeling relations in a more document-oriented fashion might be considered.
Examples
Violates
var dict = new Dictionary<Guid, User>();
var issues = session.Query<Issue>();
// Each issue generates an additional query
foreach (var i in issues)
{
var user = session.Load<User>(i.AssigneeId.Value);
dict.Add(user.Id, user);
}
Does not violate
// Issues with assignees are fetched in one round-trip.
var dict = new Dictionary<Guid, User>();
session.Query<Issue>().Include(x => x.AssigneeId, dict).ToArray();