Session: Querying: How to Perform Queries Lazily

In some situations, query execution must be delayed. To cover such a scenario, Lazily and many other query extensions have been introduced.

Lazily and LazilyAsync

Lazy<IEnumerable<T>> Lazily<T>();

Lazy<IEnumerable<T>> Lazily<T>(Action<IEnumerable<T>> onEval);

Lazy<Task<IEnumerable<T>>> LazilyAsync<T>();

Lazy<Task<IEnumerable<T>>> LazilyAsync<T>(Action<IEnumerable<T>> onEval);
Parameters
onEval Action<IEnumerable<TResult>> An action that will be performed on the query results.
Return Value
Lazy<IEnumerable<TResult>> Lazy query initializer returning query results.

Example

Lazy<IEnumerable<Employee>> employeesLazy = session
    .Query<Employee>()
    .Where(x => x.FirstName == "Robert")
    .Lazily();

IEnumerable<Employee> employees = employeesLazy.Value; // query will be executed here
Lazy<Task<IEnumerable<Employee>>> employeesLazy = session
    .Query<Employee>()
    .Where(x => x.FirstName == "Robert")
    .LazilyAsync();

IEnumerable<Employee> employees = await employeesLazy.Value; // query will be executed here

Counts

Lazy<int> CountLazily<T>();

Lazy<Task<int>> CountLazilyAsync<T>(CancellationToken token = default(CancellationToken));
Return Value
Lazy Lazy query initializer returning a count of matched documents.

Example

Lazy<int> countLazy = session
    .Query<Employee>()
    .Where(x => x.FirstName == "Robert")
    .CountLazily();

int count = countLazy.Value; // query will be executed here

Suggestions

Lazy<Dictionary<string, SuggestionResult>> ExecuteLazy(Action<Dictionary<string, SuggestionResult>> onEval = null);

Lazy<Task<Dictionary<string, SuggestionResult>>> ExecuteLazyAsync(Action<Dictionary<string, SuggestionResult>> onEval = null);
Return Value
Lazy<Dictionary<string, SuggestionResult>> Lazy query initializer containing a dictionary with suggestions for matching executed query

Example

Lazy<Dictionary<string, SuggestionResult>> suggestLazy = session
    .Query<Employee>("Employees_ByFullName")
    .SuggestUsing(builder => builder.ByField("FullName", "johne"))
    .ExecuteLazy();

Dictionary<string, SuggestionResult> suggest = suggestLazy.Value; // query will be executed here
List<string> suggestions = suggest["FullName"].Suggestions;

Facets

Lazy<Dictionary<string, FacetResult>> ExecuteLazy(Action<Dictionary<string, FacetResult>> onEval = null);

Lazy<Task<Dictionary<string, FacetResult>>> ExecuteLazyAsync(Action<Dictionary<string, FacetResult>> onEval = null);
Return Value
Lazy<Dictionary<string, FacetResult>> Lazy query initializer containing a dictionary with facet results matching executed query

Example

Lazy<Dictionary<string, FacetResult>> facetsLazy = session
    .Query<Camera>("Camera/Costs")
    .AggregateUsing("facets/CameraFacets")
    .ExecuteLazy();

Dictionary<string, FacetResult> facets = facetsLazy.Value; // query will be executed here
FacetResult results = facets["Manufacturer"];