---
title: "Perform a Lazy Query"
url: "https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-queries-lazily"
version: "6.2"
language: "csharp"
---

# Perform a Lazy Query

> Client language: C#. Also available for [Java](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-queries-lazily.java.md), [Python](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-queries-lazily.python.md), [PHP](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-queries-lazily.php.md), [Node.js](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-queries-lazily.nodejs.md).
>
> RavenDB publishes an official agent skill for coding assistants at https://docs.ravendb.net/skills/ravendb/SKILL.md (also installable with `npx skills add ravendb/skills`). The skill describes itself as: "Read this before writing any RavenDB query, client call or /databases/ request. Covers server setup, document modelling, the Node.js, .NET and Python clients, RQL, indexes, vector search and AI agents. Code written from recall tends to run and return the wrong rows, because RQL resembles SQL and the clients take field names as plain strings."

> **Note**
>
> - Query execution can be deferred: the query can be defined as **Lazy**, and executed
>   at a later time, when its results are actually needed.
>
> - This article contains examples for lazy queries. Prior to reading it, please refer
>   to [perform requests lazily](https://docs.ravendb.net/6.2/client-api/session/how-to/perform-operations-lazily.md)
>   for general knowledge about RavenDB's lazy behavior and other request types that can be
>   executed lazily within a session.
>
> - In this page:
>   - [Lazy query](#lazy-query)
>   - [Lazy count query](#lazy-count-query)
>   - [Lazy suggestions query](#lazy-suggestions-query)
>   - [Lazy facets query](#lazy-facets-query)
>   - [Syntax](#syntax)

## Lazy query

### Lazy\_query

```csharp
// Define a lazy query
Lazy<IEnumerable<Employee>> lazyEmployees = session
  .Query<Employee>()
  .Where(x => x.FirstName == "Robert")
   // Add a call to 'Lazily'
  .Lazily();

IEnumerable<Employee> employees = lazyEmployees.Value; // Query is executed here
```

### Lazy\_query\_async

```csharp
// Define a lazy query
Lazy<Task<IEnumerable<Employee>>> lazyEmployees = asyncSession
  .Query<Employee>()
  .Where(x => x.FirstName == "Robert")
   // Add a call to 'LazilyAsync'
  .LazilyAsync();

IEnumerable<Employee> employees = await lazyEmployees.Value; // Query is executed here
```

### Lazy\_documentQuery

```csharp
// Define a lazy DocumentQuery
Lazy<IEnumerable<Employee>> lazyEmployees = session.Advanced
  .DocumentQuery<Employee>()
  .WhereEquals(x => x.FirstName, "Robert")
   // Add a call to 'Lazily'
  .Lazily();

IEnumerable<Employee> employees = lazyEmployees.Value; // DocumentQuery is executed here
```

- Learn more about queries in this [query overview](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-query.md).

## Lazy count query

### Lazy\_query

```csharp
// Define a lazy count query
Lazy<int> lazyCount = session
  .Query<Employee>()
  .Where(x => x.FirstName == "Robert")
   // Add a call to 'CountLazily'
  .CountLazily();

int count = lazyCount.Value; // Query is executed here
```

### Lazy\_query\_async

```csharp
// Define a lazy count query
Lazy<Task<int>> lazyCount = asyncSession
  .Query<Employee>()
  .Where(x => x.FirstName == "Robert")
   // Add a call to 'CountLazilyAsync'
  .CountLazilyAsync();

int count = await lazyCount.Value; // Query is executed here
```

### Lazy\_documentQuery

```csharp
// Define a lazy DocumentQuery
Lazy<int> lazyCount = session.Advanced
  .DocumentQuery<Employee>()
  .WhereEquals(x => x.FirstName, "Robert")
   // Add a call to 'CountLazily'
  .CountLazily();

int count = lazyCount.Value; // DocumentQuery is executed here
```

## Lazy suggestions query

### Lazy\_query

```csharp
// Define a lazy suggestion query
Lazy<Dictionary<string, SuggestionResult>> lazySuggestions = session
  .Query<Product>()
  .SuggestUsing(builder => builder.ByField(x => x.Name, "chaig"))
   // Add a call to 'ExecuteLazy'
  .ExecuteLazy();

Dictionary<string, SuggestionResult> suggest = lazySuggestions.Value; // Query is executed here
List<string> suggestions = suggest["Name"].Suggestions;
```

### Lazy\_query\_async

```csharp
// Define a lazy suggestion query
Lazy<Task<Dictionary<string, SuggestionResult>>> lazySuggestions = asyncSession
  .Query<Employee>()
  .SuggestUsing(builder => builder.ByField("Name", "chaig"))
   // Add a call to 'ExecuteLazyAsync'
  .ExecuteLazyAsync();

Dictionary<string, SuggestionResult> suggest = await lazySuggestions.Value; // Query is executed here
List<string> suggestions = suggest["Name"].Suggestions;
```

### Lazy\_documentQuery

```csharp
// Define a lazy DocumentQuery
Lazy<Dictionary<string, SuggestionResult>> lazySuggestions = session.Advanced
  .DocumentQuery<Employee>()
  .SuggestUsing(builder => builder.ByField("Name", "chaig"))
   // Add a call to 'ExecuteLazy'
  .ExecuteLazy();

Dictionary<string, SuggestionResult> suggest = lazySuggestions.Value; // DocumentQuery is executed here
List<string> suggestions = suggest["FullName"].Suggestions;
```

- Learn more about suggestions in [query for suggestions](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-work-with-suggestions.md).

## Lazy facets query

### Lazy\_query

```csharp
// Define a lazy facets query
Lazy<Dictionary<string, FacetResult>> lazyFacets = session
  .Query<Product, Products_ByCategoryAndPrice>()
  .AggregateBy(facetsDefinition)
   // Add a call to 'ExecuteLazy'
  .ExecuteLazy();

Dictionary<string, FacetResult> facets = lazyFacets.Value; // Query is executed here

FacetResult categoryResults = facets["Product Category"];
FacetResult priceResults = facets["Price per Unit"];
```

### Lazy\_query\_async

```csharp
// Define a lazy DocumentQuery
Lazy<Task<Dictionary<string,FacetResult>>> lazyFacets = asyncSession
  .Query<Product, Products_ByCategoryAndPrice>()
  .AggregateBy(facetsDefinition)
   // Add a call to 'ExecuteLazyAsync'
  .ExecuteLazyAsync();

Dictionary<string, FacetResult> facets = await lazyFacets.Value; // Query is executed here

FacetResult categoryResults = facets["Product Category"];
FacetResult priceResults = facets["Price per Unit"];
```

### Lazy\_documentQuery

```csharp
// Define a lazy DocumentQuery
Lazy<Dictionary<string, FacetResult>> lazyFacets = session.Advanced
  .DocumentQuery<Product, Products_ByCategoryAndPrice>()
  .AggregateBy(facetsDefinition)
   // Add a call to 'ExecuteLazy'
  .ExecuteLazy();

Dictionary<string, FacetResult> facets = lazyFacets.Value; //  DocumentQuery is executed here

FacetResult categoryResults = facets["Product Category"];
FacetResult priceResults = facets["Price per Unit"];
```

### Facets\_definition

```csharp
// The facets definition used in the facets query:
List<FacetBase> facetsDefinition = new List<FacetBase>
{
  new Facet
  {
      FieldName = "CategoryName",
      DisplayFieldName = "Product Category"
  },
  new RangeFacet<Product>
  {
      Ranges =
      {
          product => product.PricePerUnit < 25,
          product => product.PricePerUnit >= 25 && product.PricePerUnit < 50,
          product => product.PricePerUnit >= 50 && product.PricePerUnit < 100,
          product => product.PricePerUnit >= 100
      },
      DisplayFieldName = "Price per Unit"
  }
};
```

### Index\_definition

```csharp
// The index definition used in the facets query:
public class Products_ByCategoryAndPrice :
  AbstractIndexCreationTask<Product, Products_ByCategoryAndPrice.IndexEntry>
{
  // The IndexEntry class defines the index-fields
  public class IndexEntry
  {
      public string CategoryName { get; set; }
      public decimal PricePerUnit { get; set; }
  }
      
  public Products_ByCategoryAndPrice()
  {
      // The 'Map' function defines the content of the index-fields
      Map = products => from product in products
          select new IndexEntry
          {
              CategoryName = LoadDocument<Category>(product.Category).Name,
              PricePerUnit = product.PricePerUnit
          };
  }
}
```

- Learn more about facets in [perform faceted search](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-perform-a-faceted-search.md).

## Syntax

```csharp
// Lazy query overloads:
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);
```

```csharp
// Lazy count query overloads:
Lazy<int> CountLazily<T>();
Lazy<long> LongCountLazily<T>();

Lazy<Task<int>> CountLazilyAsync<T>(CancellationToken token = default(CancellationToken));
Lazy<Task<long>> LongCountLazilyAsync<T>(CancellationToken token = default(CancellationToken));
```

```csharp
// Lazy suggestions query overloads:
Lazy<Dictionary<string, SuggestionResult>>
  ExecuteLazy(Action<Dictionary<string, SuggestionResult>> onEval = null);

Lazy<Task<Dictionary<string, SuggestionResult>>>
  ExecuteLazyAsync(Action<Dictionary<string, SuggestionResult>> onEval = null,
      CancellationToken token = default);
```

```csharp
// Lazy facets query overloads:
Lazy<Dictionary<string, FacetResult>>
  ExecuteLazy(Action<Dictionary<string, FacetResult>> onEval = null);

Lazy<Task<Dictionary<string, FacetResult>>>
  ExecuteLazyAsync(Action<Dictionary<string, FacetResult>> onEval = null,
      CancellationToken token = default);
```

| Parameters | Type | Description |
| - | - | - |
| **onEval** | `Action<IEnumerable<TResult>>` <br /> `Action<Dictionary<string, SuggestionResult>>` <br /> `Action<Dictionary<string, FacetResult>>` | An action that will be performed on the query results<br />when the query is executed. |

| Return Value | |
| - | - |
| `Lazy<IEnumerable<TResult>>`<br />`Lazy<int>`<br />`Lazy<Dictionary<string, SuggestionResult>>`<br />`Lazy<Dictionary<string, FacetResult>>` | A lazy instance that will evaluate the query only when needed. |

## See also

- [Query overview](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-query.md)
- [Perform requests lazily](https://docs.ravendb.net/6.2/client-api/session/how-to/perform-operations-lazily.md)
- [Querying: Basics](https://docs.ravendb.net/6.2/indexes/querying/query-index.md)
- [query for suggestions](https://docs.ravendb.net/6.2/client-api/session/querying/how-to-work-with-suggestions.md)
