Class QueryCommand<TResult>
A strongly typed query command producing TResult rows. It adds the
terminal execution surface - materialization, scalar and aggregate terminals, and set operations -
on top of the relational shape carried by QueryCommand.
public sealed class QueryCommand<TResult> : QueryCommand, IQueryRegistry, ICloneable
Type Parameters
TResultThe projected row, element or scalar type produced by the command.
- Inheritance
-
QueryCommand<TResult>
- Implements
- Inherited Members
- Extension Methods
Constructors
QueryCommand(IDataContext?, QueryDefinition)
Initializes a command of type TResult from a query shape.
public QueryCommand(IDataContext? dataProvider, QueryDefinition definition)
Parameters
dataProviderIDataContextThe context that executes the command, or
nullwhen the command is an unbound clone.definitionQueryDefinitionThe shape (projection, filtering, joins, grouping, sorting and provider clauses) to copy from.
Methods
Any()
Returns true when the query produces at least one row.
public bool Any()
Returns
- bool
trueif at least one row exists; otherwisefalse.
Any(params ReadOnlySpan<object?>)
Returns true when the query produces at least one row, binding the supplied parameters.
public bool Any(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- bool
trueif at least one row exists; otherwisefalse.
AnyAsync(params object[])
Asynchronously returns true when the query produces at least one row, using the default cancellation token.
public Task<bool> AnyAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
AnyAsync(CancellationToken, params object[])
Asynchronously returns true when the query produces at least one row.
public Task<bool> AnyAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
AsCte(string)
Wraps this command as an ordinary (non-recursive) common table expression declared under
name. The returned descriptor is read with
From<TResult>(IDataContext, Cte<TResult>); the CTE keeps this command as
its body and the projection shape TResult as its readable columns, so
member access on the typed source resolves to this command's output columns. The descriptor is a
typed projection source, not a mapped entity. Recursion is not part of this API: use the legacy
WithRecursive string API for recursive CTEs.
public Cte<TResult> AsCte(string name)
Parameters
namestringThe name the CTE is declared under and referenced by in
from.
Returns
- Cte<TResult>
An immutable descriptor of the declared CTE.
Exceptions
- ArgumentException
nameisnullor empty.
AsRecursiveCte(string, Func<CteReference<TResult>, QueryCommand<TResult>>)
Wraps this command as the anchor of a recursive common table expression declared under
name. step is invoked exactly once, during this
call, with a typed self-reference bound to the anchor's shape; the returned step query is
combined with the anchor as anchor UNION ALL step. The descriptor is read with
From<TResult>(IDataContext, Cte<TResult>). No recursion-depth hint is
emitted by this overload. Legacy WithRecursive behavior is unchanged.
public Cte<TResult> AsRecursiveCte(string name, Func<CteReference<TResult>, QueryCommand<TResult>> step)
Parameters
namestringThe name the CTE is declared under and referenced by in
from.stepFunc<CteReference<TResult>, QueryCommand<TResult>>Builds the recursive step from the typed self-reference; invoked once.
Returns
- Cte<TResult>
An immutable descriptor of the recursive CTE.
Exceptions
- ArgumentException
nameisnullor empty.- ArgumentNullException
stepis null.- InvalidOperationException
stepreturned null.
AsRecursiveCte(string, Func<CteReference<TResult>, QueryCommand<TResult>>, int)
Wraps this command as the anchor of a recursive common table expression with an explicit
recursion-depth limit. See the two-argument AsRecursiveCte overload for the callback
contract. maxRecursion is required (no default): it is
rendered only by dialects that expose a depth option (SQL Server
option (maxrecursion n)) and ignored by the others, matching legacy WithRecursive
semantics; omitting the hint is expressed by the two-argument overload.
public Cte<TResult> AsRecursiveCte(string name, Func<CteReference<TResult>, QueryCommand<TResult>> step, int maxRecursion)
Parameters
namestringThe name the CTE is declared under and referenced by in
from.stepFunc<CteReference<TResult>, QueryCommand<TResult>>Builds the recursive step from the typed self-reference; invoked once.
maxRecursionintThe recursion-depth limit (SQL Server
maxrecursion n); required.
Returns
- Cte<TResult>
An immutable descriptor of the recursive CTE.
Exceptions
- ArgumentException
nameisnullor empty.- ArgumentNullException
stepis null.- InvalidOperationException
stepreturned null.
CreateAsyncEnumerator(params object[]?)
Prepares the command and returns an async enumerator over its rows.
public IAsyncEnumerator<TResult> CreateAsyncEnumerator(params object[]? @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- IAsyncEnumerator<TResult>
An async enumerator over the result rows.
CreateAsyncEnumerator(CancellationToken, params object[]?)
Prepares the command and returns an async enumerator over its rows.
public IAsyncEnumerator<TResult> CreateAsyncEnumerator(CancellationToken cancellationToken, params object[]? @params)
Parameters
cancellationTokenCancellationTokenA token observed while preparing and while enumerating rows.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- IAsyncEnumerator<TResult>
An async enumerator over the result rows.
CreateEnumeratorAsync(params object[]?)
Prepares the command and returns a task producing a synchronous row enumerator.
public Task<IEnumerator<TResult>> CreateEnumeratorAsync(params object[]? @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<IEnumerator<TResult>>
A task producing an enumerator over the result rows.
CreateEnumeratorAsync(CancellationToken, params object[]?)
Prepares the command and returns a task producing a synchronous row enumerator.
public Task<IEnumerator<TResult>> CreateEnumeratorAsync(CancellationToken cancellationToken, params object[]? @params)
Parameters
cancellationTokenCancellationTokenA token observed while preparing and opening the reader.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<IEnumerator<TResult>>
A task producing an enumerator over the result rows.
CreateSelf()
Creates an empty command of the same concrete type, bound to this command's context.
protected override QueryCommand CreateSelf()
Returns
- QueryCommand
A new command used as the clone destination.
CreateSelfForClone()
Creates an empty command of the same concrete type with the cache-safe parts of the shape, used to build a cached clone.
protected override QueryCommand CreateSelfForClone()
Returns
- QueryCommand
A new command with projections, conditions and grouping stripped for the plan cache.
Distinct()
Returns a clone of this command that emits DISTINCT, removing duplicate rows from the result.
public QueryCommand<TResult> Distinct()
Returns
- QueryCommand<TResult>
A new command marked distinct.
ExceptAll<T>(QueryCommand<T>)
Returns a clone of this command combined with queryCommand through EXCEPT ALL (duplicates preserved).
public QueryCommand<TResult> ExceptAll<T>(QueryCommand<T> queryCommand)
Parameters
queryCommandQueryCommand<T>The second operand of the set operation.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TThe project type of the second operand.
ExceptAll<TEntity>(Expression<Func<TEntity, TResult>>)
Returns a clone of this command combined with the rows projected from TEntity by selector through EXCEPT ALL (duplicates preserved).
public QueryCommand<TResult> ExceptAll<TEntity>(Expression<Func<TEntity, TResult>> selector)
Parameters
selectorExpression<Func<TEntity, TResult>>Projection from
TEntitytoTResult; must not be null.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TEntityThe entity type of the second operand's source.
Remarks
This overload is syntactic sugar for ExceptAll(_dataContext.From<TEntity>().Select(selector)):
it fixes the element type of the right operand to TResult (the left side's type).
A bare ExceptAll(null) is ambiguous between
ExceptAll<T>(QueryCommand<T>) and this overload's
Expression<Func<TEntity, TResult>> parameter; the caller resolves it with a typed
null — (QueryCommand<TResult>)null! selects the command overload, while
(Expression<Func<TEntity, TResult>>)null! selects this selector overload (which
then throws ArgumentNullException).
Exceptions
- ArgumentNullException
selectoris null.- InvalidOperationException
This command is not bound to a data context.
Except<T>(QueryCommand<T>)
Returns a clone of this command combined with queryCommand through EXCEPT (distinct rows of this command not present in the other).
public QueryCommand<TResult> Except<T>(QueryCommand<T> queryCommand)
Parameters
queryCommandQueryCommand<T>The second operand of the set operation.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TThe project type of the second operand.
Except<TEntity>(Expression<Func<TEntity, TResult>>)
Returns a clone of this command combined with the rows projected from TEntity by selector through EXCEPT (distinct rows of this command not present in the other).
public QueryCommand<TResult> Except<TEntity>(Expression<Func<TEntity, TResult>> selector)
Parameters
selectorExpression<Func<TEntity, TResult>>Projection from
TEntitytoTResult; must not be null.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TEntityThe entity type of the second operand's source.
Remarks
This overload is syntactic sugar for Except(_dataContext.From<TEntity>().Select(selector)):
it fixes the element type of the right operand to TResult (the left side's type).
A bare Except(null) is ambiguous between
Except<T>(QueryCommand<T>) and this overload's
Expression<Func<TEntity, TResult>> parameter; the caller resolves it with a typed
null — (QueryCommand<TResult>)null! selects the command overload, while
(Expression<Func<TEntity, TResult>>)null! selects this selector overload (which
then throws ArgumentNullException).
Exceptions
- ArgumentNullException
selectoris null.- InvalidOperationException
This command is not bound to a data context.
ExecuteScalar(params ReadOnlySpan<object?>)
Executes the command and returns the first column of the first row as a scalar.
public TResult? ExecuteScalar(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The scalar value, or
nullwhen the query returns no rows.
ExecuteScalarAsync(CancellationToken, params object[])
Asynchronously executes the command and returns the first column of the first row as a scalar.
public Task<TResult?> ExecuteScalarAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the scalar value, or
nullwhen the query returns no rows.
First()
Returns the first row of the query and throws when it produces none.
public TResult First()
Returns
- TResult
The first result row.
First(params ReadOnlySpan<object?>)
Returns the first row of the query, binding the supplied parameters, and throws when it produces none.
public TResult First(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The first result row.
FirstAsync(params object[])
Asynchronously returns the first row of the query, using the default cancellation token, and throws when it produces none.
public Task<TResult> FirstAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the first result row.
FirstAsync(CancellationToken, params object[])
Asynchronously returns the first row of the query and throws when it produces none.
public Task<TResult> FirstAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the first result row.
FirstOrDefault()
Returns the first row of the query, or the default value when it produces none.
public TResult? FirstOrDefault()
Returns
- TResult
The first result row, or the default value for the element type.
FirstOrDefault(params ReadOnlySpan<object?>)
Returns the first row of the query, binding the supplied parameters, or the default value when it produces none.
public TResult? FirstOrDefault(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The first result row, or the default value for the element type.
FirstOrDefaultAsync(params object[])
Asynchronously returns the first row of the query using the default cancellation token, or the default value when it produces none.
public Task<TResult?> FirstOrDefaultAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the first result row, or the default value for the element type.
FirstOrDefaultAsync(CancellationToken, params object[])
Asynchronously returns the first row of the query, or the default value when it produces none.
public Task<TResult?> FirstOrDefaultAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the first result row, or the default value for the element type.
ForJson(ForJsonMode, string?, bool, params object[]?)
Executes the query and returns the whole result set as one JSON document (SQL Server
FOR JSON). The projection drives the document shape in Path and
the table structure drives it in Auto; the query's own element type is
irrelevant because the database returns a single document column. This is a terminal operator,
so it does not apply an implicit TOP 1: the document covers the entire result set.
public string? ForJson(ForJsonMode mode = ForJsonMode.Path, string? root = null, bool includeNullValues = false, params object[]? @params)
Parameters
modeForJsonModeWhether the output is shaped by the projection aliases (Path) or the table structure (Auto).
rootstringAn optional
ROOT('name')wrapper around the document, ornullfor none.includeNullValuesboolWhether null-valued properties are emitted (
INCLUDE_NULL_VALUES).paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- string
The JSON document, or
nullwhen the query produced no rows (SQL ServerFOR JSONyields SQL NULL for an empty result set).
ForJsonAsync(ForJsonMode, string?, bool, CancellationToken, params object[]?)
Asynchronously executes the query and returns the whole result set as one JSON document (SQL Server FOR JSON).
public Task<string?> ForJsonAsync(ForJsonMode mode = ForJsonMode.Path, string? root = null, bool includeNullValues = false, CancellationToken cancellationToken = default, params object[]? @params)
Parameters
modeForJsonModeWhether the output is shaped by the projection aliases (Path) or the table structure (Auto).
rootstringAn optional
ROOT('name')wrapper around the document, ornullfor none.includeNullValuesboolWhether null-valued properties are emitted (
INCLUDE_NULL_VALUES).cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
ForXml(ForXmlMode, string?, string?, bool, params object[]?)
Executes the query and returns the whole result set as one XML document (SQL Server
FOR XML). This is a terminal operator, so it does not apply an implicit TOP 1: the
document covers the entire result set.
public string? ForXml(ForXmlMode mode = ForXmlMode.Path, string? elementName = null, string? root = null, bool elements = false, params object[]? @params)
Parameters
modeForXmlModeThe
FOR XMLshaping mode (RAW,AUTO,EXPLICITorPATH).elementNamestringThe row element name for
RAW/PATH, ornullfor the default.rootstringAn optional
ROOT('name')wrapper around the document, ornullfor none.elementsboolWhether columns are emitted as child elements (
ELEMENTS).paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- string
The XML document, or
nullwhen the query produced no rows.
ForXmlAsync(ForXmlMode, string?, string?, bool, CancellationToken, params object[]?)
Asynchronously executes the query and returns the whole result set as one XML document (SQL Server FOR XML).
public Task<string?> ForXmlAsync(ForXmlMode mode = ForXmlMode.Path, string? elementName = null, string? root = null, bool elements = false, CancellationToken cancellationToken = default, params object[]? @params)
Parameters
modeForXmlModeThe
FOR XMLshaping mode (RAW,AUTO,EXPLICITorPATH).elementNamestringThe row element name for
RAW/PATH, ornullfor the default.rootstringAn optional
ROOT('name')wrapper around the document, ornullfor none.elementsboolWhether columns are emitted as child elements (
ELEMENTS).cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
Hint(params string[])
Returns a new command carrying statement-level query hints, for example SQL Server
"recompile" (rendered as OPTION (recompile)). Repeated calls accumulate hints.
A dialect that does not support query hints rejects a command that carries them when its SQL
is built.
public QueryCommand<TResult> Hint(params string[] hints)
Parameters
hintsstring[]
Returns
- QueryCommand<TResult>
IntersectAll<T>(QueryCommand<T>)
Returns a clone of this command combined with queryCommand through INTERSECT ALL (duplicates preserved).
public QueryCommand<TResult> IntersectAll<T>(QueryCommand<T> queryCommand)
Parameters
queryCommandQueryCommand<T>The second operand of the set operation.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TThe project type of the second operand.
IntersectAll<TEntity>(Expression<Func<TEntity, TResult>>)
Returns a clone of this command combined with the rows projected from TEntity by selector through INTERSECT ALL (duplicates preserved).
public QueryCommand<TResult> IntersectAll<TEntity>(Expression<Func<TEntity, TResult>> selector)
Parameters
selectorExpression<Func<TEntity, TResult>>Projection from
TEntitytoTResult; must not be null.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TEntityThe entity type of the second operand's source.
Remarks
This overload is syntactic sugar for IntersectAll(_dataContext.From<TEntity>().Select(selector)):
it fixes the element type of the right operand to TResult (the left side's type).
A bare IntersectAll(null) is ambiguous between
IntersectAll<T>(QueryCommand<T>) and this overload's
Expression<Func<TEntity, TResult>> parameter; the caller resolves it with a typed
null — (QueryCommand<TResult>)null! selects the command overload, while
(Expression<Func<TEntity, TResult>>)null! selects this selector overload (which
then throws ArgumentNullException).
Exceptions
- ArgumentNullException
selectoris null.- InvalidOperationException
This command is not bound to a data context.
Intersect<T>(QueryCommand<T>)
Returns a clone of this command combined with queryCommand through INTERSECT (distinct rows present in both operands).
public QueryCommand<TResult> Intersect<T>(QueryCommand<T> queryCommand)
Parameters
queryCommandQueryCommand<T>The second operand of the set operation.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TThe project type of the second operand.
Intersect<TEntity>(Expression<Func<TEntity, TResult>>)
Returns a clone of this command combined with the rows projected from TEntity by selector through INTERSECT (distinct rows present in both operands).
public QueryCommand<TResult> Intersect<TEntity>(Expression<Func<TEntity, TResult>> selector)
Parameters
selectorExpression<Func<TEntity, TResult>>Projection from
TEntitytoTResult; must not be null.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TEntityThe entity type of the second operand's source.
Remarks
This overload is syntactic sugar for Intersect(_dataContext.From<TEntity>().Select(selector)):
it fixes the element type of the right operand to TResult (the left side's type).
A bare Intersect(null) is ambiguous between
Intersect<T>(QueryCommand<T>) and this overload's
Expression<Func<TEntity, TResult>> parameter; the caller resolves it with a typed
null — (QueryCommand<TResult>)null! selects the command overload, while
(Expression<Func<TEntity, TResult>>)null! selects this selector overload (which
then throws ArgumentNullException).
Exceptions
- ArgumentNullException
selectoris null.- InvalidOperationException
This command is not bound to a data context.
Last()
Returns the last row of the ordered query and throws when it produces none. Requires an ORDER BY.
public TResult Last()
Returns
- TResult
The last result row.
Last(params ReadOnlySpan<object?>)
Returns the last row of the ordered query, binding the supplied parameters, and throws when it produces none. Requires an ORDER BY.
public TResult Last(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The last result row.
LastAsync(params object[])
Asynchronously returns the last row of the ordered query using the default cancellation token, and throws when it produces none. Requires an ORDER BY.
public Task<TResult> LastAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the last result row.
LastAsync(CancellationToken, params object[])
Asynchronously returns the last row of the ordered query and throws when it produces none. Requires an ORDER BY.
public Task<TResult> LastAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the last result row.
LastOrDefault()
Returns the last row of the ordered query, or the default value when it produces none. Requires an ORDER BY.
public TResult? LastOrDefault()
Returns
- TResult
The last result row, or the default value for the element type.
LastOrDefault(params ReadOnlySpan<object?>)
Returns the last row of the ordered query, binding the supplied parameters, or the default value when it produces none. Requires an ORDER BY.
public TResult? LastOrDefault(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The last result row, or the default value for the element type.
LastOrDefaultAsync(params object[])
Asynchronously returns the last row of the ordered query using the default cancellation token, or the default value when it produces none. Requires an ORDER BY.
public Task<TResult?> LastOrDefaultAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the last result row, or the default value for the element type.
LastOrDefaultAsync(CancellationToken, params object[])
Asynchronously returns the last row of the ordered query, or the default value when it produces none. Requires an ORDER BY.
public Task<TResult?> LastOrDefaultAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the last result row, or the default value for the element type.
Limit(int)
Returns a clone of this command with the maximum number of returned rows set. Unlike the builder-level limit this applies after the projection, so a grouped/aggregated query does not need the aggregate repeated in an outer query.
public QueryCommand<TResult> Limit(int limit)
Parameters
limitintThe maximum number of rows to return; zero means no limit.
Returns
- QueryCommand<TResult>
A new command carrying the limit.
Offset(int)
Returns a clone of this command with the number of leading rows to skip set.
public QueryCommand<TResult> Offset(int offset)
Parameters
offsetintThe number of leading rows to skip; zero starts from the first row.
Returns
- QueryCommand<TResult>
A new command carrying the offset.
OrderBy(int)
Returns a clone of this command with the 1-based column added to its sort order in ascending direction.
public QueryCommand<TResult> OrderBy(int columnIndex)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
OrderBy(int, NullsPosition)
Returns a clone of this command with the 1-based projected column appended to its sort order in the ascending direction and the requested NULL placement.
public QueryCommand<TResult> OrderBy(int columnIndex, NullsPosition nullsPosition)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
OrderBy(int, OrderDirection)
Returns a clone of this command with a 1-based projected column added to its sort order.
public QueryCommand<TResult> OrderBy(int columnIndex, OrderDirection direction)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
directionOrderDirectionThe sort direction.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
OrderBy(int, OrderDirection, NullsPosition)
Returns a clone of this command with the 1-based projected column appended to its sort order in the given direction and the requested NULL placement.
public QueryCommand<TResult> OrderBy(int columnIndex, OrderDirection direction, NullsPosition nullsPosition)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
directionOrderDirectionThe sort direction.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
OrderBy(Expression<Func<TResult, object?>>)
Returns a clone of this command with orderExp added to its sort order in ascending direction.
public QueryCommand<TResult> OrderBy(Expression<Func<TResult, object?>> orderExp)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
OrderBy(Expression<Func<TResult, object?>>, NullsPosition)
Returns a clone of this command with orderExp appended to its sort order in the
ascending direction and the requested NULL placement. Appending never replaces the existing keys.
public QueryCommand<TResult> OrderBy(Expression<Func<TResult, object?>> orderExp, NullsPosition nullsPosition)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
OrderBy(Expression<Func<TResult, object?>>, OrderDirection)
Returns a clone of this command with orderExp added to its sort order. The
expression is written over the projected result type (TResult); each
member is resolved to the projection expression that produced the corresponding output column.
Repeated calls append keys, so the existing order is preserved.
public QueryCommand<TResult> OrderBy(Expression<Func<TResult, object?>> orderExp, OrderDirection direction)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
directionOrderDirectionThe sort direction.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
OrderBy(Expression<Func<TResult, object?>>, OrderDirection, NullsPosition)
Returns a clone of this command with orderExp appended to its sort order in the
given direction and the requested NULL placement. Appending never replaces the existing keys.
public QueryCommand<TResult> OrderBy(Expression<Func<TResult, object?>> orderExp, OrderDirection direction, NullsPosition nullsPosition)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
directionOrderDirectionThe sort direction.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
OrderByDescending(int)
Returns a clone of this command with the 1-based column added to its sort order in descending direction.
public QueryCommand<TResult> OrderByDescending(int columnIndex)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
OrderByDescending(int, NullsPosition)
Returns a clone of this command with the 1-based projected column appended to its sort order in the descending direction and the requested NULL placement.
public QueryCommand<TResult> OrderByDescending(int columnIndex, NullsPosition nullsPosition)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
OrderByDescending(Expression<Func<TResult, object?>>)
Returns a clone of this command with orderExp added to its sort order in descending direction.
public QueryCommand<TResult> OrderByDescending(Expression<Func<TResult, object?>> orderExp)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
OrderByDescending(Expression<Func<TResult, object?>>, NullsPosition)
Returns a clone of this command with orderExp appended to its sort order in the
descending direction and the requested NULL placement.
public QueryCommand<TResult> OrderByDescending(Expression<Func<TResult, object?>> orderExp, NullsPosition nullsPosition)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
Page(int, int)
Returns a clone of this command with both the page size and the start position set.
public QueryCommand<TResult> Page(int limit, int offset)
Parameters
limitintThe maximum number of rows to return; zero means no limit.
offsetintThe number of leading rows to skip; zero starts from the first row.
Returns
- QueryCommand<TResult>
A new command carrying the limit and offset.
Pipeline(params object[])
Streams the result set asynchronously using the default cancellation token.
public IAsyncEnumerable<TResult> Pipeline(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- IAsyncEnumerable<TResult>
An async stream of the result rows.
Pipeline(CancellationToken, params object[])
Streams the result set asynchronously. The previous implementation ran the synchronous
ToEnumerable(params object[]) on a thread-pool thread and pushed every row through an
unbounded Channel: it blocked a pool thread for the whole result set, buffered the
entire result in memory when the consumer was slower, and observed cancellation only
between rows. Driving the async enumerator directly keeps the same semantics without the
extra thread and without the unbounded buffer.
public IAsyncEnumerable<TResult> Pipeline(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenparamsobject[]
Returns
- IAsyncEnumerable<TResult>
Prepare(PrepareOptions, CancellationToken)
Prepares the command so it can be executed repeatedly, typically with different parameter values.
public IPreparedQueryCommand<TResult> Prepare(PrepareOptions options = default, CancellationToken cancellationToken = default)
Parameters
optionsPrepareOptionsHow the prepared command reuses its underlying command and whether rows are streamed. The default value prepares a buffered command whose underlying command is reused per connection.
cancellationTokenCancellationTokenA token to cancel preparation.
Returns
- IPreparedQueryCommand<TResult>
The prepared query command.
Exceptions
- ArgumentOutOfRangeException
optionscarries a PreparedCommandCache value that is not defined.
PrepareCommand(bool, CancellationToken)
Prepares the command and records TResult in the result plan. The result
type hash is folded into the plan key only when dontCalculateHash is false.
public override void PrepareCommand(bool dontCalculateHash, CancellationToken cancellationToken)
Parameters
dontCalculateHashboolWhen
true, skips recomputing the plan hashes; the caller promises the shape is unchanged.cancellationTokenCancellationTokenA token to cancel preparation.
Single()
Returns the only row of the query and throws when it produces zero or more than one row.
public TResult Single()
Returns
- TResult
The single result row.
Single(params ReadOnlySpan<object?>)
Returns the only row of the query, binding the supplied parameters, and throws when it produces zero or more than one row.
public TResult Single(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The single result row.
SingleAsync(params object[])
Asynchronously returns the only row of the query using the default cancellation token, and throws when it produces zero or more than one row.
public Task<TResult> SingleAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the single result row.
SingleAsync(CancellationToken, params object[])
Asynchronously returns the only row of the query and throws when it produces zero or more than one row.
public Task<TResult> SingleAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the single result row.
SingleOrDefault()
Returns the only row of the query, or the default value when it produces no rows; throws when it produces more than one.
public TResult? SingleOrDefault()
Returns
- TResult
The single result row, or the default value for the element type when there is none.
SingleOrDefault(params ReadOnlySpan<object?>)
Returns the only row of the query, binding the supplied parameters, or the default value when it produces no rows; throws when it produces more than one.
public TResult? SingleOrDefault(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult
The single result row, or the default value for the element type when there is none.
SingleOrDefaultAsync(params object[])
Asynchronously returns the only row of the query using the default cancellation token, or the default value when it produces no rows; throws when it produces more than one.
public Task<TResult?> SingleOrDefaultAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the single result row, or the default value for the element type when there is none.
SingleOrDefaultAsync(CancellationToken, params object[])
Asynchronously returns the only row of the query, or the default value when it produces no rows; throws when it produces more than one.
public Task<TResult?> SingleOrDefaultAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult>
A task producing the single result row, or the default value for the element type when there is none.
ThenBy(int)
Returns a clone of this command with the 1-based projected column appended to its sort order in the ascending direction. The key is appended after every existing key.
public QueryCommand<TResult> ThenBy(int columnIndex)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
ThenBy(int, NullsPosition)
Returns a clone of this command with the 1-based projected column appended to its sort order in the ascending direction and the requested NULL placement.
public QueryCommand<TResult> ThenBy(int columnIndex, NullsPosition nullsPosition)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
ThenBy(int, OrderDirection)
Returns a clone of this command with the 1-based projected column appended to its sort order in the given direction.
public QueryCommand<TResult> ThenBy(int columnIndex, OrderDirection direction)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
directionOrderDirectionThe sort direction.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
ThenBy(int, OrderDirection, NullsPosition)
Returns a clone of this command with the 1-based projected column appended to its sort order in the given direction and the requested NULL placement.
public QueryCommand<TResult> ThenBy(int columnIndex, OrderDirection direction, NullsPosition nullsPosition)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
directionOrderDirectionThe sort direction.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
ThenBy(Expression<Func<TResult, object?>>)
Returns a clone of this command with orderExp appended to its sort order in the
ascending direction. Unlike a second OrderBy, this states explicitly that the key is a
secondary one; both append to the same key list, so the resulting order is identical.
public QueryCommand<TResult> ThenBy(Expression<Func<TResult, object?>> orderExp)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
ThenBy(Expression<Func<TResult, object?>>, NullsPosition)
Returns a clone of this command with orderExp appended to its sort order in the
ascending direction and the requested NULL placement.
public QueryCommand<TResult> ThenBy(Expression<Func<TResult, object?>> orderExp, NullsPosition nullsPosition)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
ThenBy(Expression<Func<TResult, object?>>, OrderDirection)
Returns a clone of this command with orderExp appended to its sort order in the
given direction. The key is appended after every existing key, never replaces one.
public QueryCommand<TResult> ThenBy(Expression<Func<TResult, object?>> orderExp, OrderDirection direction)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
directionOrderDirectionThe sort direction.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
ThenBy(Expression<Func<TResult, object?>>, OrderDirection, NullsPosition)
Returns a clone of this command with orderExp appended to its sort order in the
given direction and the requested NULL placement.
public QueryCommand<TResult> ThenBy(Expression<Func<TResult, object?>> orderExp, OrderDirection direction, NullsPosition nullsPosition)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
directionOrderDirectionThe sort direction.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
ThenByDescending(int)
Returns a clone of this command with the 1-based projected column appended to its sort order in the descending direction.
public QueryCommand<TResult> ThenByDescending(int columnIndex)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
ThenByDescending(int, NullsPosition)
Returns a clone of this command with the 1-based projected column appended to its sort order in the descending direction and the requested NULL placement.
public QueryCommand<TResult> ThenByDescending(int columnIndex, NullsPosition nullsPosition)
Parameters
columnIndexintThe 1-based index of the projected column to sort by; must be greater than zero.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
ThenByDescending(Expression<Func<TResult, object?>>)
Returns a clone of this command with orderExp appended to its sort order in the
descending direction.
public QueryCommand<TResult> ThenByDescending(Expression<Func<TResult, object?>> orderExp)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
ThenByDescending(Expression<Func<TResult, object?>>, NullsPosition)
Returns a clone of this command with orderExp appended to its sort order in the
descending direction and the requested NULL placement.
public QueryCommand<TResult> ThenByDescending(Expression<Func<TResult, object?>> orderExp, NullsPosition nullsPosition)
Parameters
orderExpExpression<Func<TResult, object>>The key selector over the projected result.
nullsPositionNullsPositionWhere SQL
NULLvalues are placed for this key.
Returns
- QueryCommand<TResult>
A new command carrying the added sort.
Exceptions
- ArgumentOutOfRangeException
nullsPositionis not a defined NullsPosition member.
ToArray()
Executes the command and materializes every row into an array, binding no parameters.
public TResult[] ToArray()
Returns
- TResult[]
An array containing all result rows.
Remarks
The parameterless form is the expression-tree-usable terminal: the params ReadOnlySpan<object?>
overload is a ref struct and an expanded params collection, so a query expression tree that ends in
ToArray() cannot reference it (CS8640/CS9226). Both overloads execute the identical
command; a zero-argument call simply takes this one.
ToArray(params ReadOnlySpan<object?>)
Executes the command and materializes every row into an array.
public TResult[] ToArray(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- TResult[]
An array containing all result rows.
ToArrayAsync(params object[])
Executes the command asynchronously and materializes every row into an array, using the default cancellation token.
public Task<TResult[]> ToArrayAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult[]>
A task producing an array of all result rows.
ToArrayAsync(CancellationToken, params object[])
Executes the command asynchronously and materializes every row into an array.
public Task<TResult[]> ToArrayAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<TResult[]>
A task producing an array of all result rows.
ToAsyncEnumerable(params object[])
Returns the result set as an async stream using the default cancellation token.
public IAsyncEnumerable<TResult> ToAsyncEnumerable(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- IAsyncEnumerable<TResult>
An async stream of the result rows.
ToAsyncEnumerable(CancellationToken, params object[])
Returns the result set as an async stream, using the supplied cancellation token.
public IAsyncEnumerable<TResult> ToAsyncEnumerable(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token observed while enumerating rows.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- IAsyncEnumerable<TResult>
An async stream of the result rows.
ToDictionaryAsync<TKey>(Func<TResult, TKey>, IEqualityComparer<TKey>?, CancellationToken, params object[])
Executes the command asynchronously and materializes the rows into a dictionary keyed by keySelector.
public Task<Dictionary<TKey, TResult>> ToDictionaryAsync<TKey>(Func<TResult, TKey> keySelector, IEqualityComparer<TKey>? comparer, CancellationToken cancellationToken, params object[] @params) where TKey : notnull
Parameters
keySelectorFunc<TResult, TKey>Maps a row to its dictionary key; keys must be unique.
comparerIEqualityComparer<TKey>The equality comparer used to compare keys, or
nullto use the default comparer.cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<Dictionary<TKey, TResult>>
A task producing a dictionary of all result rows.
Type Parameters
TKeyThe dictionary key type.
ToDictionaryAsync<TKey>(Func<TResult, TKey>, params object[])
Executes the command asynchronously and materializes the rows into a dictionary keyed by keySelector, using the default cancellation token.
public Task<Dictionary<TKey, TResult>> ToDictionaryAsync<TKey>(Func<TResult, TKey> keySelector, params object[] @params) where TKey : notnull
Parameters
keySelectorFunc<TResult, TKey>Maps a row to its dictionary key; keys must be unique.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<Dictionary<TKey, TResult>>
A task producing a dictionary of all result rows.
Type Parameters
TKeyThe dictionary key type.
ToDictionaryAsync<TKey>(Func<TResult, TKey>, CancellationToken, params object[])
Executes the command asynchronously and materializes the rows into a dictionary keyed by keySelector.
public Task<Dictionary<TKey, TResult>> ToDictionaryAsync<TKey>(Func<TResult, TKey> keySelector, CancellationToken cancellationToken, params object[] @params) where TKey : notnull
Parameters
keySelectorFunc<TResult, TKey>Maps a row to its dictionary key; keys must be unique.
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- Task<Dictionary<TKey, TResult>>
A task producing a dictionary of all result rows.
Type Parameters
TKeyThe dictionary key type.
ToDictionary<TKey>(Func<TResult, TKey>, IEqualityComparer<TKey>?, params ReadOnlySpan<object?>)
Executes the command and materializes the rows into a dictionary keyed by keySelector.
public Dictionary<TKey, TResult> ToDictionary<TKey>(Func<TResult, TKey> keySelector, IEqualityComparer<TKey>? comparer, params ReadOnlySpan<object?> @params) where TKey : notnull
Parameters
keySelectorFunc<TResult, TKey>Maps a row to its dictionary key; keys must be unique.
comparerIEqualityComparer<TKey>The equality comparer used to compare keys, or
nullto use the default comparer.paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- Dictionary<TKey, TResult>
A dictionary containing all result rows.
Type Parameters
TKeyThe dictionary key type.
ToDictionary<TKey>(Func<TResult, TKey>, params ReadOnlySpan<object?>)
Executes the command and materializes the rows into a dictionary keyed by keySelector.
public Dictionary<TKey, TResult> ToDictionary<TKey>(Func<TResult, TKey> keySelector, params ReadOnlySpan<object?> @params) where TKey : notnull
Parameters
keySelectorFunc<TResult, TKey>Maps a row to its dictionary key; keys must be unique.
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- Dictionary<TKey, TResult>
A dictionary containing all result rows.
Type Parameters
TKeyThe dictionary key type.
ToEnumerable(params object[])
Executes the command and returns the result set as a synchronous sequence.
public IEnumerable<TResult> ToEnumerable(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
- IEnumerable<TResult>
A sequence over the result rows.
ToHashSet(IEqualityComparer<TResult>?, params ReadOnlySpan<object?>)
Executes the command and materializes the rows into a hash set that uses the supplied comparison.
public HashSet<TResult> ToHashSet(IEqualityComparer<TResult>? comparer, params ReadOnlySpan<object?> @params)
Parameters
comparerIEqualityComparer<TResult>The equality comparer used to compare rows, or
nullto use the default comparer.paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- HashSet<TResult>
A set containing all result rows.
ToHashSet(params ReadOnlySpan<object?>)
Executes the command and materializes the rows into a hash set.
public HashSet<TResult> ToHashSet(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- HashSet<TResult>
A set containing all result rows.
ToHashSetAsync(IEqualityComparer<TResult>?, CancellationToken, params object[])
Executes the command asynchronously and materializes the rows into a hash set that uses the supplied comparison.
public Task<HashSet<TResult>> ToHashSetAsync(IEqualityComparer<TResult>? comparer, CancellationToken cancellationToken, params object[] @params)
Parameters
comparerIEqualityComparer<TResult>The equality comparer used to compare rows, or
nullto use the default comparer.cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
ToHashSetAsync(params object[])
Executes the command asynchronously and materializes the rows into a hash set, using the default cancellation token.
public Task<HashSet<TResult>> ToHashSetAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
ToHashSetAsync(CancellationToken, params object[])
Executes the command asynchronously and materializes the rows into a hash set.
public Task<HashSet<TResult>> ToHashSetAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
ToList()
Executes the command and materializes every row into a list, binding no parameters.
public List<TResult> ToList()
Returns
- List<TResult>
A list containing all result rows.
Remarks
The parameterless form is the expression-tree-usable terminal: the params ReadOnlySpan<object?>
overload is a ref struct and an expanded params collection, so a query expression tree that ends in
ToList() cannot reference it (CS8640/CS9226). Both overloads execute the identical
command; a zero-argument call simply takes this one.
ToList(params ReadOnlySpan<object?>)
Executes the command and materializes every row into a list.
public List<TResult> ToList(params ReadOnlySpan<object?> @params)
Parameters
paramsReadOnlySpan<object>Positional parameter values, bound in the order they appear in the SQL.
Returns
- List<TResult>
A list containing all result rows.
ToListAsync(params object[])
Executes the command asynchronously and materializes every row into a list, using the default cancellation token.
public Task<List<TResult>> ToListAsync(params object[] @params)
Parameters
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
ToListAsync(CancellationToken, params object[])
Executes the command asynchronously and materializes every row into a list.
public Task<List<TResult>> ToListAsync(CancellationToken cancellationToken, params object[] @params)
Parameters
cancellationTokenCancellationTokenA token to cancel the query.
paramsobject[]Positional parameter values, bound in the order they appear in the SQL.
Returns
UnionAll<T>(QueryCommand<T>)
Returns a clone of this command combined with queryCommand through UNION ALL (duplicates preserved).
public QueryCommand<TResult> UnionAll<T>(QueryCommand<T> queryCommand)
Parameters
queryCommandQueryCommand<T>The second operand of the set operation.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TThe project type of the second operand.
UnionAll<TEntity>(Expression<Func<TEntity, TResult>>)
Returns a clone of this command combined with the rows projected from TEntity by selector through UNION ALL (duplicates preserved).
public QueryCommand<TResult> UnionAll<TEntity>(Expression<Func<TEntity, TResult>> selector)
Parameters
selectorExpression<Func<TEntity, TResult>>Projection from
TEntitytoTResult; must not be null.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TEntityThe entity type of the second operand's source.
Remarks
This overload is syntactic sugar for UnionAll(_dataContext.From<TEntity>().Select(selector)):
it fixes the element type of the right operand to TResult (the left side's type).
A bare UnionAll(null) is ambiguous between
UnionAll<T>(QueryCommand<T>) and this overload's
Expression<Func<TEntity, TResult>> parameter; the caller resolves it with a typed
null — (QueryCommand<TResult>)null! selects the command overload, while
(Expression<Func<TEntity, TResult>>)null! selects this selector overload (which
then throws ArgumentNullException).
Exceptions
- ArgumentNullException
selectoris null.- InvalidOperationException
This command is not bound to a data context.
Union<T>(QueryCommand<T>)
Returns a clone of this command combined with queryCommand through UNION (duplicates removed).
public QueryCommand<TResult> Union<T>(QueryCommand<T> queryCommand)
Parameters
queryCommandQueryCommand<T>The second operand of the set operation.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TThe project type of the second operand.
Union<TEntity>(Expression<Func<TEntity, TResult>>)
Returns a clone of this command combined with the rows projected from TEntity by selector through UNION (duplicates removed).
public QueryCommand<TResult> Union<TEntity>(Expression<Func<TEntity, TResult>> selector)
Parameters
selectorExpression<Func<TEntity, TResult>>Projection from
TEntitytoTResult; must not be null.
Returns
- QueryCommand<TResult>
A new command carrying the set operation.
Type Parameters
TEntityThe entity type of the second operand's source.
Remarks
This overload is syntactic sugar for Union(_dataContext.From<TEntity>().Select(selector)):
it fixes the element type of the right operand to TResult (the left side's type).
A bare Union(null) is ambiguous between
Union<T>(QueryCommand<T>) and this overload's
Expression<Func<TEntity, TResult>> parameter; the caller resolves it with a typed
null — (QueryCommand<TResult>)null! selects the command overload, while
(Expression<Func<TEntity, TResult>>)null! selects this selector overload (which
then throws ArgumentNullException).
Exceptions
- ArgumentNullException
selectoris null.- InvalidOperationException
This command is not bound to a data context.
WithCommandTimeout(int)
Overrides the command timeout in seconds for this command: the value is applied to the
underlying database command and takes precedence over the context default set with
DataContextBuilder.UseCommandTimeout. A value of zero or less means the provider default.
The override participates in the plan-cache key, so two otherwise identical commands with
different timeouts do not share a cached command and the value never leaks to another command.
public QueryCommand<TResult> WithCommandTimeout(int seconds)
Parameters
secondsintThe command timeout in seconds; zero or less uses the provider default.
Returns
- QueryCommand<TResult>
A new command carrying the timeout override.
WithForJson(ForJsonMode, string?, bool)
Attaches a SQL Server FOR JSON clause so the whole result set is returned as one JSON
document (FOR JSON PATH by default), and returns the command for further composition or
SQL inspection. Prefer ForJson(ForJsonMode, string?, bool, params object[]?) to execute
the query and read the document. A dialect that does not support the clause rejects the command
when its SQL is built.
public QueryCommand<TResult> WithForJson(ForJsonMode mode = ForJsonMode.Path, string? root = null, bool includeNullValues = false)
Parameters
modeForJsonModeWhether the output is shaped by the projection aliases (Path) or the table structure (Auto).
rootstringAn optional
ROOT('name')wrapper around the document, ornullfor none.includeNullValuesboolWhether null-valued properties are emitted (
INCLUDE_NULL_VALUES).
Returns
- QueryCommand<TResult>
A new command carrying the
FOR JSONclause.
WithForXml(ForXmlMode, string?, string?, bool)
Attaches a SQL Server FOR XML clause so the whole result set is returned as one XML
document (FOR XML PATH by default), and returns the command for further composition or
SQL inspection. Prefer ForXml(ForXmlMode, string?, string?, bool, params object[]?) to
execute the query and read the document. A dialect that does not support the clause rejects the
command when its SQL is built, and combining it with WithForJson(ForJsonMode, string?, bool) throws.
public QueryCommand<TResult> WithForXml(ForXmlMode mode = ForXmlMode.Path, string? elementName = null, string? root = null, bool elements = false)
Parameters
modeForXmlModeThe
FOR XMLshaping mode (RAW,AUTO,EXPLICITorPATH).elementNamestringThe row element name for
RAW/PATH, ornullfor the default.rootstringAn optional
ROOT('name')wrapper around the document, ornullfor none.elementsboolWhether columns are emitted as child elements (
ELEMENTS).
Returns
- QueryCommand<TResult>
A new command carrying the
FOR XMLclause.
WithKeywordCase(KeywordCase)
Overrides the letter case in which this command's SQL keywords are emitted: Upper renders
SELECT ... FROM ..., Lower renders select ... from .... Without a call the
command inherits the context default set with DataContextBuilder.UseKeywordCase.
Identifiers, string literals, function names, type names and raw SQL are never affected.
public QueryCommand<TResult> WithKeywordCase(KeywordCase keywordCase = KeywordCase.Upper)
Parameters
keywordCaseKeywordCase
Returns
- QueryCommand<TResult>
WithNamingConvention(INamingConvention?)
Overrides the naming convention for this command: auto-derived table and column names are
translated through convention (for example
Instance), while names declared with
[SqlTable]/[Column] or a fluent mapping stay verbatim. Without a call the command
inherits the context default set with DataContextBuilder.UseNamingConvention.
public QueryCommand<TResult> WithNamingConvention(INamingConvention? convention)
Parameters
conventionINamingConvention
Returns
- QueryCommand<TResult>
WithQuotedIdentifiers(bool)
Overrides identifier quoting for this command: when value is true,
physical table and column names are quoted with the provider's delimiter ("id" on
PostgreSQL/SQLite, [id] on SQL Server, `id` on MySQL/MariaDB/ClickHouse); when
false, names are emitted verbatim. Without a call the command inherits the context
default set with DataContextBuilder.UseQuotedIdentifiers.
public QueryCommand<TResult> WithQuotedIdentifiers(bool value = true)
Parameters
valuebool
Returns
- QueryCommand<TResult>
WithTag(string?)
Returns a new command carrying a query tag, rendered as a block comment (/* tag /)
immediately after the SELECT keyword so the statement is identifiable in logs, profilers
and server-side query stores. The tag is independent of Hint(params string[]): it is
a plain comment, not an optimizer hint, and it is rendered on every SQL provider. Line breaks and
the comment delimiters / and /* are neutralised, so the tag cannot break out of the
comment. The tag is part of the plan key; passing null or an empty string clears it.
public QueryCommand<TResult> WithTag(string? tag)
Parameters
tagstringThe tag text to render, or
nullto clear the tag.
Returns
- QueryCommand<TResult>
A new command carrying the tag.
WriteJson(Stream)
Writes the query's projected rows directly to destination as a JSON array,
without materializing a TResult per row. The destination is owned by the
caller and is never closed. Supported on database providers only.
public void WriteJson(Stream destination)
Parameters
destinationStreamThe caller-owned output stream; it is never closed. On a read, serialization or destination error, or on cancellation, the operation stops and the original exception propagates; already-written bytes are left in place (no rollback and no recovery tail), the destination stays open, and the writer never adds a
Stream.Flushcall.
Exceptions
- NotSupportedException
The command is executed by the in-memory provider.
WriteJson(Stream, JsonStreamOptions)
Writes the query's projected rows directly to destination as JSON using
options, without materializing a TResult per row. The
destination is owned by the caller and is never closed. Supported on database providers only.
public void WriteJson(Stream destination, JsonStreamOptions options)
Parameters
destinationStreamThe caller-owned output stream; it is never closed. On a read, serialization or destination error, or on cancellation, the operation stops and the original exception propagates; already-written bytes are left in place (no rollback and no recovery tail), the destination stays open, and the writer never adds a
Stream.Flushcall.optionsJsonStreamOptionsThe JSON container and shaping options.
Exceptions
- NotSupportedException
The command is executed by the in-memory provider, the projection shape is not supported, or the option combination is invalid.
WriteJson(Stream, JsonStreamOptions, CancellationToken, params ReadOnlySpan<object?>)
Writes the query's projected rows directly to stream as JSON using
options and binding the positional SQL parameter values in
params, without materializing a TResult per row. The
destination is owned by the caller and is never closed. Supported on database providers only.
public void WriteJson(Stream stream, JsonStreamOptions options, CancellationToken cancellationToken, params ReadOnlySpan<object?> @params)
Parameters
streamStreamThe caller-owned output stream; it is never closed. On a read, serialization or destination error, or on cancellation, the operation stops and the original exception propagates; already-written bytes are left in place (no rollback and no recovery tail), the destination stays open, and the writer never adds a
Stream.Flushcall.optionsJsonStreamOptionsThe JSON container and shaping options.
cancellationTokenCancellationTokenA token observed while preparing, reading rows and writing to the stream.
paramsReadOnlySpan<object>The positional SQL parameter values, in the order their placeholders appear. An empty set binds nothing; a null element binds DBNull.
Exceptions
- NotSupportedException
The command is executed by the in-memory provider, the projection shape is not supported, or the option combination is invalid.
- ArgumentNullException
streamoroptionsis null.
WriteJsonAsync(Stream, JsonStreamOptions, CancellationToken)
Asynchronously writes the query's projected rows directly to destination as
JSON using options, without materializing a TResult per
row. The destination is owned by the caller and is never closed. Supported on database providers only.
public Task WriteJsonAsync(Stream destination, JsonStreamOptions options, CancellationToken cancellationToken = default)
Parameters
destinationStreamThe caller-owned output stream; it is never closed. On a read, serialization or destination error, or on cancellation, the operation stops and the original exception propagates; already-written bytes are left in place (no rollback and no recovery tail), the destination stays open, and the writer never adds a
Stream.Flushcall.optionsJsonStreamOptionsThe JSON container and shaping options.
cancellationTokenCancellationTokenA token observed while reading rows and writing to the stream.
Returns
- Task
A task that completes when the whole document has been written.
Exceptions
- NotSupportedException
The command is executed by the in-memory provider, the projection shape is not supported, or the option combination is invalid.
WriteJsonAsync(Stream, JsonStreamOptions, CancellationToken, params object?[])
Asynchronously writes the query's projected rows directly to stream as JSON
using options and binding the positional SQL parameter values in
params, without materializing a TResult per row. The
destination is owned by the caller and is never closed. Supported on database providers only.
public Task WriteJsonAsync(Stream stream, JsonStreamOptions options, CancellationToken cancellationToken, params object?[] @params)
Parameters
streamStreamThe caller-owned output stream; it is never closed. On a read, serialization or destination error, or on cancellation, the operation stops and the original exception propagates; already-written bytes are left in place (no rollback and no recovery tail), the destination stays open, and the writer never adds a
Stream.Flushcall.optionsJsonStreamOptionsThe JSON container and shaping options.
cancellationTokenCancellationTokenA token observed while preparing, reading rows and writing to the stream.
paramsobject[]The positional SQL parameter values, in the order their placeholders appear. An empty set binds nothing; a null element binds DBNull.
Returns
- Task
A task that completes when the whole document has been written.
Exceptions
- NotSupportedException
The command is executed by the in-memory provider, the projection shape is not supported, or the option combination is invalid.
- ArgumentNullException
streamoroptionsis null.
WriteJsonAsync(Stream, CancellationToken)
Asynchronously writes the query's projected rows directly to destination as a
JSON array, without materializing a TResult per row. The destination is
owned by the caller and is never closed. Supported on database providers only.
public Task WriteJsonAsync(Stream destination, CancellationToken cancellationToken = default)
Parameters
destinationStreamThe caller-owned output stream; it is never closed. On a read, serialization or destination error, or on cancellation, the operation stops and the original exception propagates; already-written bytes are left in place (no rollback and no recovery tail), the destination stays open, and the writer never adds a
Stream.Flushcall.cancellationTokenCancellationTokenA token observed while reading rows and writing to the stream.
Returns
- Task
A task that completes when the whole document has been written.
Exceptions
- NotSupportedException
The command is executed by the in-memory provider.