Skip to Content
TORMQueries, projection and paging

Conditions, projections and paging

On this page

Run the complete example

Install TORM and TORM.Sqlite as described in quick start. Replace Program.cs with this code and run dotnet run. It creates an in-memory database and three devices, so every run starts with the same data.

using TORM; await using var db = new OrmClient(new ConnectionConfig { DatabaseType = DatabaseType.Sqlite, ConnectionString = "Data Source=:memory:" }); await db.CodeFirst!.InitTableAsync<Device>(); await db.InsertableRange(new[] { new Device { Id = 1, Code = "P-001", Name = "Inlet pump", Enabled = true }, new Device { Id = 2, Code = "P-002", Name = "Outlet pump", Enabled = false }, new Device { Id = 3, Code = "P-003", Name = "Circulation pump", Enabled = true } }).ExecuteAsync(); var keyword = "pump"; var enabled = await db.Queryable<Device>() .Where(x => x.Enabled) .WhereIF(!string.IsNullOrWhiteSpace(keyword), x => x.Name.Contains(keyword)) .OrderBy(x => x.Id) .ToListAsync(); Console.WriteLine($"Filtered: {string.Join(", ", enabled.Select(x => x.Code))}"); var names = await db.Queryable<Device>() .Where(x => x.Enabled) .OrderBy(x => x.Id) .Select(x => new DeviceName { Id = x.Id, Name = x.Name }) .ToListAsync(); Console.WriteLine($"Names: {string.Join(", ", names.Select(x => x.Name))}"); var page = await db.Queryable<Device>() .OrderBy(x => x.Id) .ToPageListAsync(pageNumber: 1, pageSize: 2); Console.WriteLine($"Page: {page.Current}/{page.Pages}, total: {page.Total}"); Console.WriteLine($"Records: {string.Join(", ", page.Records.Select(x => x.Code))}"); var first = await db.Queryable<Device>().Where(x => x.Enabled).ToCursorPageAsync(1); Console.WriteLine($"Cursor 1: {first.Records[0].Code}, more: {first.HasMore}"); if (first.HasMore) { var next = await db.Queryable<Device>().Where(x => x.Enabled) .ToCursorPageAsync(1, first.NextCursor); Console.WriteLine($"Cursor 2: {next.Records[0].Code}, more: {next.HasMore}"); } await foreach (var device in db.Queryable<Device>().OrderBy(x => x.Id).ToAsyncEnumerable()) { Console.WriteLine($"Stream: {device.Code}"); } /// <summary>查询教程使用固定主键,保证分页结果可复现。</summary> [OrmTable("query_devices")] public sealed class Device { /// <summary>由示例显式指定的唯一主键。</summary> [OrmColumn(IsPrimaryKey = true)] public long Id { get; set; } /// <summary>设备的字符串业务编码。</summary> [OrmColumn(Length = 64, IsNullable = NullableState.Nullable)] public string Code { get; set; } = ""; /// <summary>参与关键词筛选的名称。</summary> [OrmColumn(Length = 128, IsNullable = NullableState.Nullable)] public string Name { get; set; } = ""; /// <summary>决定设备是否进入启用列表。</summary> [OrmColumn(IsNullable = NullableState.Nullable)] public bool Enabled { get; set; } } /// <summary>只返回页面需要的设备字段。</summary> public sealed class DeviceName { /// <summary>保留设备身份,供后续操作定位记录。</summary> public long Id { get; set; } /// <summary>用于列表展示的设备名称。</summary> public string Name { get; set; } = ""; }

Expected output:

Filtered: P-001, P-003 Names: Inlet pump, Circulation pump Page: 1/2, total: 3 Records: P-001, P-002 Cursor 1: P-001, more: True Cursor 2: P-003, more: False Stream: P-001 Stream: P-002 Stream: P-003

Choose the result shape

TaskAPIResult and cost
Check whether a device existsAnyAsync()bool, without loading an entity
Retrieve one device by keyFirstAsync()Entity or null; handle a missing record
Return a bounded listToListAsync()Materializes the complete result
Show page numbers and a totalToPageListAsync()PagedList<T>, including a count query
Load the next batchToCursorPageAsync()CursorPage<T>, without a total count
Process many records sequentiallyToAsyncEnumerable()Holds the reader and connection during enumeration

Conditions and DTO projections

WhereIF adds a condition only when its first argument is true. Setting the example’s keyword to an empty string removes the name filter but retains Enabled. Expressions translate to SQL; arbitrary C# methods and object logic may not translate.

Select retrieves only the required columns. Named DTOs make public response contracts and AOT metadata easier to maintain. See mapping and API reference for mapped properties and supported expressions.

List APIs: filter and project before paging

When a page needs names, apply its filter, projection and limit in the database. Add this fragment before the complete program’s type declarations. It retrieves only Id and Name for enabled devices while retaining paging information:

var requestedPage = 1; var requestedSize = 2; if (requestedPage < 1) throw new ArgumentOutOfRangeException(nameof(requestedPage), "Page number must be positive."); if (requestedSize is < 1 or > 200) throw new ArgumentOutOfRangeException(nameof(requestedSize), "Invalid page request."); using var pageCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var enabledPage = await db.Queryable<Device>() .Where(x => x.Enabled) .OrderBy(x => x.Id) .Select(x => new DeviceName { Id = x.Id, Name = x.Name }) .ToPageListAsync(requestedPage, requestedSize, pageCancellation.Token); Console.WriteLine($"Enabled page: {enabledPage.Current}/{enabledPage.Pages}, total: {enabledPage.Total}"); Console.WriteLine($"Projected IDs: {string.Join(", ", enabledPage.Records.Select(x => x.Id))}");

It appends:

Enabled page: 1/1, total: 2 Projected IDs: 1, 3

This single-table query counts records before fetching the page; DTO projection only reduces returned columns. Data can change between the two queries. Use suitable transaction isolation when the total and records require one snapshot.

Page numbers and cursors

pageNumber starts at 1. Records contains the page, Total the complete count, and Current, Size, Pages the page number, page size and total pages. Page numbers below 1 become 1; sizes below 1 become 10. Set an application page-size limit and use stable ordering that includes a unique key.

Deep offset pages can scan or skip earlier records. Use cursors for successive batches.

ChoiceCount and orderUse case
ToPageListAsyncIncludes totals; caller supplies stable ordering and may project DTOsJump to pages, show totals, sort by business fields
ToCursorPageAsyncNo count; full entities in internal physical-table and complete-primary-key orderSuccessive batches under a fixed filter
ToAsyncEnumerableNo paging wrapper; caller supplies filters, order and projectionSequential export or processing while holding a connection

Cursors require primary keys and parameterized queries. Do not add OrderBy, Skip, Take, projections, aggregation or Distinct. The implementation reads at most one extra record to determine HasMore; it does not calculate Total. Internal ordering across split tables is not a global event-time order.

Walk a cursor to completion

Add this fragment before the type declarations too. Each iteration creates a new query with the same filter and parameters, then finishes processing its batch before fetching another:

using var cursorCancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30)); string? cursor = null; var batchNumber = 0; while (true) { var batch = await db.Queryable<Device>() .Where(x => x.Enabled) .ToCursorPageAsync(1, cursor, cursorCancellation.Token); Console.WriteLine($"Cursor batch {++batchNumber}: {string.Join(", ", batch.Records.Select(x => x.Code))}"); if (!batch.HasMore) break; cursor = batch.NextCursor ?? throw new InvalidOperationException("A continuation cursor was expected."); }

Adding this fragment alone appends:

Cursor batch 1: P-001 Cursor batch 2: P-003

Smaller batches increase round trips; larger batches retain more entities. An empty result ends traversal.

Use null first, return NextCursor unchanged and stop when HasMore is false. Restart after changing filters, parameters, connections or logical tables; mismatched or malformed tokens are rejected. Cursors provide neither authorization nor cross-page snapshots, so reapply data-permission filters on every request. Do not parse, construct or log tokens.

Inspect SQL and consume streams

To inspect a translated expression, add this before the type declarations in the program:

var command = db.Queryable<Device>().Where(x => x.Code == "P-001").ToSql(); Console.WriteLine(command.Sql); Console.WriteLine($"Parameter count: {command.Parameters.Count}");

ToSql() returns SQL and a parameter dictionary without executing the query. ToSqlAsync() is also available when actual split-table discovery is involved. Inspect parameter binding alongside SQL, and handle sensitive values according to your logging policy.

Do not execute another command on the same OrmClient inside a streaming loop. Finish enumeration first, or create a separate client for independent operations. Calling ToListAsync() and then looping processes an in-memory list rather than streaming from the database. See connection lifetime for cancellation and ownership.

Builders accumulate conditions and query shape. Create them per request rather than sharing a mutable query across concurrent requests. When requesting multiple results, account for each execution’s database work.

Reduce query time and allocation

See performance and benchmarks for measurements across four databases and API selection. Bound retained objects and pending tasks during row-by-row processing.

SymptomCheck
A narrow DTO but a slow APIMeasure count, page fetch and serialization separately; inspect actual database plans
Duplicate or missing records across pagesUnique ordering and concurrent writes; address ordering and snapshot consistency separately
Cursor throws InvalidOperationExceptionPrimary keys, parameterization and incompatible ordering, projection or offset paging
A continuation token is rejectedChanged filter values, condition construction, connection or table; do not rebuild the token
Row-by-row processing retains substantial memoryGrowing lists, retained pages or unbounded concurrent work