Table of Contents

Class DataContext

Namespace
NextORM.Core
Assembly
nextorm.core.dll

Base class for database-backed contexts. Owns the connection lifecycle, the shared query-plan cache and the execution/planning collaborators, and exposes the terminal operators over prepared commands. Providers derive from it and supply the SQL dialect, the connection factory and parameter creation.

public abstract class DataContext : IDataContext, IQueryExecutor, IQueryMaterializer, IQueryPlanner, IRowReaderFactory, IQueryCache, IContextEnvironment, IRawCommandExecutor, IAsyncDisposable, IDisposable, IConnectionManager, ITransactionManager
Inheritance
DataContext
Implements
Derived
Inherited Members
Extension Methods

Constructors

DataContext(DataContextBuilder)

Creates a context from builder options (logger factory, mapping mode, naming convention and identifier quoting). The connection is created lazily by the provider on first use.

public DataContext(DataContextBuilder optionsBuilder)

Parameters

optionsBuilder DataContextBuilder

The options collected from DataContextBuilder.

DataContext(string?, DbConnection?, DataContextBuilder)

Creates a context with an optional connection string or a caller-supplied connection. A string produces a connection the context owns and disposes; a supplied connection is used as-is and is not disposed by the context (the caller keeps ownership).

protected DataContext(string? connectionString, DbConnection? providedConnection, DataContextBuilder optionsBuilder)

Parameters

connectionString string

Connection string used to create a context-owned connection, or null.

providedConnection DbConnection

An already-created connection owned by the caller, or null.

optionsBuilder DataContextBuilder

The options collected from DataContextBuilder.

DataContext(string?, DbConnection?, DataContextBuilder, Version?)

Creates a context as DataContext(string?, DbConnection?, DataContextBuilder) and snapshots the provider server serverVersion once. A version-aware provider passes it here and builds its dialect from ServerVersion.

protected DataContext(string? connectionString, DbConnection? providedConnection, DataContextBuilder optionsBuilder, Version? serverVersion)

Parameters

connectionString string

Connection string used to create a context-owned connection, or null.

providedConnection DbConnection

An already-created connection owned by the caller, or null.

optionsBuilder DataContextBuilder

The options collected from DataContextBuilder.

serverVersion Version

The provider server version to snapshot, or null for unset.

Properties

AnyCommand

Lazily created, cached Any query for this context, or null until it is first needed. Caching it lets repeated existence checks reuse one prepared command.

public Lazy<QueryCommand<bool>>? AnyCommand { get; set; }

Property Value

Lazy<QueryCommand<bool>>

CommandLogger

Logger category used to trace executed commands and their parameters.

public ILogger? CommandLogger { get; }

Property Value

ILogger

CommandTimeout

The context-wide default command timeout in seconds (set with DataContextBuilder.UseCommandTimeout), or null when no timeout is configured and the provider default applies. A command can override it with WithCommandTimeout.

public int? CommandTimeout { get; }

Property Value

int?

ConnectionString

The connection string of the supplied connection, or the one the context was built with.

public string ConnectionString { get; }

Property Value

string

Dialect

SQL dialect used to render queries. Supplied by the provider; SQL generation depends on this interface rather than on the context itself.

public abstract ISqlDialect Dialect { get; }

Property Value

ISqlDialect

EagerLoadMode

The context-wide default eager-load strategy applied to LoadWith collections when a query declares no explicit mode (set with DataContextBuilder.UseEagerLoadMode). Defaults to SplitQuery. A query-level LoadWith(..., mode) overrides it.

public EagerLoadMode EagerLoadMode { get; }

Property Value

EagerLoadMode

KeywordCase

The letter case in which this context emits SQL keywords by default (set with DataContextBuilder.UseKeywordCase). A command can override it with WithKeywordCase.

public KeywordCase KeywordCase { get; }

Property Value

KeywordCase

LogSensitiveData

Whether sensitive parameter values may be logged. Kept for provider subclasses.

protected bool LogSensitiveData { get; }

Property Value

bool

Logger

Logger for the context's own diagnostic messages, or null when no logger factory was configured.

public ILogger? Logger { get; }

Property Value

ILogger

MultilineBatchSql

Whether rendered batch SQL places each statement on its own line (set with DataContextBuilder.UseMultilineBatchSql). Defaults to false (statements joined on one line with "; ").

public bool MultilineBatchSql { get; }

Property Value

bool

NamingConvention

Convention applied to auto-derived table and column names by default (set with DataContextBuilder.UseNamingConvention), or null to emit CLR names verbatim. A command can override it with WithNamingConvention.

public INamingConvention? NamingConvention { get; }

Property Value

INamingConvention

NeedMapping

Whether projected rows must be materialised into CLR objects.

public bool NeedMapping { get; }

Property Value

bool

Properties

User-owned bag of arbitrary state attached to this context.

public Dictionary<string, object> Properties { get; }

Property Value

Dictionary<string, object>

QueryCacheEnabled

Whether prepared plans may be stored in and reused from the plan cache. Initialized from DataContextBuilder.UseQueryCache (default true); setting it to false makes every preparation pass storeInCache: false without touching the sticky Cache flag on a shared command.

public bool QueryCacheEnabled { get; set; }

Property Value

bool

QuoteIdentifiers

Whether this context quotes physical identifiers by default (set with DataContextBuilder.UseQuotedIdentifiers). A command can override it with WithQuotedIdentifiers.

public bool QuoteIdentifiers { get; }

Property Value

bool

ServerVersion

The provider server version this context was configured for, or null when the provider is version-agnostic (the default). Snapshotted once at construction and immutable for the context's lifetime; a version-aware provider builds its dialect from it.

protected Version? ServerVersion { get; }

Property Value

Version

SupportsRawRowColumns

True when the provider can surface a PostgreSQL-style anonymous record or a caller-registered named composite as a single raw result-set column (see RawMapperFactory.GetOrBuild). The default is false so the PostgreSQL raw-row detection and its diagnostics stay confined to the provider that produces such columns; every other provider keeps its existing scalar/entity raw path.

protected virtual bool SupportsRawRowColumns { get; }

Property Value

bool

TimeOnlyProjectionRefusal

The refusal a TimeOnly projection raises for this provider, or null when the provider has a verified native time-of-day reader.

A context that does not override this refuses the projection: an unverified reader arm is never assumed to work, and the refusal is raised while the row mapper is composed and again in the scalar terminal, so a provider cannot end up "supported" because a driver happened to hand back a TimeOnly.

protected virtual string? TimeOnlyProjectionRefusal { get; }

Property Value

string

Methods

AddInterceptor(IConnectionInterceptor)

Registers a connection interceptor on this context instance, after the ones configured on the builder. See IConnectionInterceptor for the lifecycle it observes.

public void AddInterceptor(IConnectionInterceptor interceptor)

Parameters

interceptor IConnectionInterceptor

The interceptor to register; must not be null.

Exceptions

ArgumentNullException

interceptor is null.

AddInterceptor(IQueryInterceptor)

Registers a query interceptor on this context instance, after the ones configured on the builder. See IQueryInterceptor for the lifecycle it observes.

public void AddInterceptor(IQueryInterceptor interceptor)

Parameters

interceptor IQueryInterceptor

The interceptor to register; must not be null.

Exceptions

ArgumentNullException

interceptor is null.

ApplyProcedureParameterMetadata(DbParameter, ProcedureParameter)

Applies a descriptor's non-default ParameterDirection, DbType and size to an already-minted provider parameter. Shared by the command-unaware CreateProcedureParameter(ProcedureParameter) and the provider command-aware override (MySqlDataContext) so both procedure paths apply the same metadata rule.

protected static DbParameter ApplyProcedureParameterMetadata(DbParameter dbParameter, ProcedureParameter parameter)

Parameters

dbParameter DbParameter

The provider parameter to configure.

parameter ProcedureParameter

The descriptor carrying the metadata.

Returns

DbParameter

dbParameter, configured from parameter.

BulkInsertRows(string, IReadOnlyList<string>, IReadOnlyList<IPropertyMetadata>, IEnumerable<object?[]>, int?, int?, Action<int>?, int, BulkCopyFlags)

Writes rows through the provider's native bulk API. The default throws: a provider opts in by setting ISqlDialect.SupportsBulkCopy and overriding this method (and BulkInsertRowsAsync(string, IReadOnlyList<string>, IReadOnlyList<IPropertyMetadata>, IAsyncEnumerable<object?[]>, int?, int?, Action<int>?, int, BulkCopyFlags, CancellationToken)). The column names are already convention-resolved (unquoted); the table reference is already convention-resolved, schema-qualified and quoted when configured.

protected virtual int BulkInsertRows(string tableName, IReadOnlyList<string> columnNames, IReadOnlyList<IPropertyMetadata> columns, IEnumerable<object?[]> rows, int? commandTimeoutSeconds, int? maxBatchSize, Action<int>? progress, int notifyEvery, BulkCopyFlags bulkCopy)

Parameters

tableName string

The rendered target table reference (schema-qualified, quoted when configured).

columnNames IReadOnlyList<string>

The convention-resolved (unquoted) written column names, in row order.

columns IReadOnlyList<IPropertyMetadata>

The mapped columns, in row order (for CLR types and identity flags).

rows IEnumerable<object[]>

The rows to write; each array matches columnNames by ordinal.

commandTimeoutSeconds int?

The command timeout in seconds, or null for the provider default.

maxBatchSize int?

The maximum rows per batch, or null for the provider default.

progress Action<int>

The progress callback, called with the cumulative written-row count, or null.

notifyEvery int

The progress reporting interval in rows; the provider drives its cadence from it.

bulkCopy BulkCopyFlags

The bulk-copy flags requested by the caller; only the provider's native path can express them.

Returns

int

The number of rows written.

Exceptions

NotSupportedException

The provider has no native bulk implementation.

BulkInsertRowsAsync(string, IReadOnlyList<string>, IReadOnlyList<IPropertyMetadata>, IAsyncEnumerable<object?[]>, int?, int?, Action<int>?, int, BulkCopyFlags, CancellationToken)

Asynchronously writes rows through the provider's native bulk API.

protected virtual Task<int> BulkInsertRowsAsync(string tableName, IReadOnlyList<string> columnNames, IReadOnlyList<IPropertyMetadata> columns, IAsyncEnumerable<object?[]> rows, int? commandTimeoutSeconds, int? maxBatchSize, Action<int>? progress, int notifyEvery, BulkCopyFlags bulkCopy, CancellationToken cancellationToken)

Parameters

tableName string

The rendered target table reference (schema-qualified, quoted when configured).

columnNames IReadOnlyList<string>

The convention-resolved (unquoted) written column names, in row order.

columns IReadOnlyList<IPropertyMetadata>

The mapped columns, in row order (for CLR types and identity flags).

rows IAsyncEnumerable<object[]>

The rows to write; each array matches columnNames by ordinal.

commandTimeoutSeconds int?

The command timeout in seconds, or null for the provider default.

maxBatchSize int?

The maximum rows per batch, or null for the provider default.

progress Action<int>

The progress callback, called with the cumulative written-row count, or null.

notifyEvery int

The progress reporting interval in rows; the provider drives its cadence from it.

bulkCopy BulkCopyFlags

The bulk-copy flags requested by the caller; only the provider's native path can express them.

cancellationToken CancellationToken

Cancels execution.

Returns

Task<int>

A task producing the number of rows written.

Exceptions

NotSupportedException

The provider has no native bulk implementation.

CreateAsyncEnumerator<TResult>(IPreparedQueryCommand<TResult>, object[]?, CancellationToken)

Creates an async enumerator that streams the prepared command's rows.

public IAsyncEnumerator<TResult> CreateAsyncEnumerator<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to enumerate.

params object[]

Positional parameters bound to the command, or null.

cancellationToken CancellationToken

Token used to cancel enumeration.

Returns

IAsyncEnumerator<TResult>

An async enumerator over the result rows.

Type Parameters

TResult

The projected result type.

CreateCommand(string)

Creates a command bound to the current connection with sql as its text. The caller owns the returned command.

public DbCommand CreateCommand(string sql)

Parameters

sql string

The SQL text to execute.

Returns

DbCommand

A new command on the current connection, bound to the active transaction when one is enlisted.

CreateDbConnection(string?)

Creates the provider-specific connection. Called only when no connection was supplied.

protected abstract DbConnection CreateDbConnection(string? connectionString)

Parameters

connectionString string

Returns

DbConnection

CreateEnumerator<TResult>(IPreparedQueryCommand<TResult>, object[]?)

Creates a synchronous enumerator over the prepared command's rows.

public IEnumerator<TResult> CreateEnumerator<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to enumerate.

params object[]

Positional parameters bound to the command, or null.

Returns

IEnumerator<TResult>

A synchronous enumerator over the result rows.

Type Parameters

TResult

The projected result type.

CreateParam(DbCommand, string, object?)

Creates a provider-specific parameter from the command the parameter is bound to. The default delegates to CreateParam(string, object?), preserving every provider's current behaviour; a provider whose ADO driver rejects parameters minted by another driver (for example MySQL with MySql.Data vs MySqlConnector) overrides this to call command.CreateParameter().

protected virtual DbParameter CreateParam(DbCommand command, string name, object? value)

Parameters

command DbCommand

The executing command the parameter will be added to.

name string

The parameter name, without the provider's prefix.

value object

The parameter value, or null.

Returns

DbParameter

A new database parameter.

CreateParam(string, object?)

Creates a provider-specific parameter with the given name and value.

public abstract DbParameter CreateParam(string name, object? value)

Parameters

name string

The parameter name, without the provider's prefix.

value object

The parameter value, or null.

Returns

DbParameter

A new database parameter.

CreateProcedureParameter(ProcedureParameter)

Creates a provider-specific parameter from a ProcedureParameter descriptor: it delegates name/value to CreateParam(string, object?) and then applies the descriptor's ParameterDirection, DbType and size. Providers with extra parameter options (for example SQL Server structured parameters) override this.

protected virtual DbParameter CreateProcedureParameter(ProcedureParameter parameter)

Parameters

parameter ProcedureParameter

The parameter descriptor.

Returns

DbParameter

A new database parameter configured from parameter.

Exceptions

ArgumentException

parameter.Name is null, empty or whitespace.

NotSupportedException

The descriptor requests a structured parameter type the provider does not support.

CreateProcedureParameter(DbCommand, ProcedureParameter)

Command-aware variant of CreateProcedureParameter(ProcedureParameter) used by the raw/procedure execution paths: it receives the command the parameter will be added to, so a provider whose ADO driver rejects a parameter minted by another driver can mint it through command.CreateParameter(). The default delegates to the command-unaware overload, preserving every provider's existing behavior; MySqlDataContext overrides it.

protected virtual DbParameter CreateProcedureParameter(DbCommand command, ProcedureParameter parameter)

Parameters

command DbCommand

The executing command the parameter will be added to.

parameter ProcedureParameter

The parameter descriptor.

Returns

DbParameter

A new database parameter configured from parameter.

Exceptions

ArgumentException

parameter.Name is null, empty or whitespace.

NotSupportedException

The descriptor requests a structured parameter type the provider does not support.

Dispose()

Closes the context-owned connection and raises Disposed. Safe to call more than once.

public void Dispose()

Dispose(bool)

Releases the connection owned by the context and raises Disposed. Called from Dispose(); disposing is true for managed cleanup.

protected virtual void Dispose(bool disposing)

Parameters

disposing bool

true when invoked from Dispose().

DisposeAsync()

Asynchronously releases the context. Delegates to Dispose() so cleanup runs exactly once.

public ValueTask DisposeAsync()

Returns

ValueTask

A completed task.

EnsureConnectionOpen()

Opens the connection if it is not already open.

public void EnsureConnectionOpen()

EnsureConnectionOpenAsync(CancellationToken)

Opens the connection if it is not already open, honouring cancellationToken while opening.

public Task EnsureConnectionOpenAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Token used to cancel a slow connection open.

Returns

Task

A task that completes once the connection is open.

ExecuteProcedure(string, params IReadOnlyList<ProcedureParameter>)

Executes the stored procedure name with parameters and returns a ProcedureResult owning the reader and command. The command is sent with StoredProcedure.

public ProcedureResult ExecuteProcedure(string name, params IReadOnlyList<ProcedureParameter> parameters)

Parameters

name string

The procedure name, passed to the provider as-is.

parameters IReadOnlyList<ProcedureParameter>

The procedure parameters (input, output, input/output and return value).

Returns

ProcedureResult

The result, which must be disposed to release the reader and command.

Remarks

Name. name is not escaped, quoted or parameterised — it is set as the command's text. Never pass untrusted input as the procedure name. Parameter names are supplied without the provider's prefix (for example @ for SQL Server).

PostgreSQL. Npgsql maps StoredProcedure to CALL name(...), which invokes a procedure (PostgreSQL 11+), not a function. Call a function through ExecuteRaw(string, params IReadOnlyList<ProcedureParameter>) instead (for example select * from f(@a)). An OUT/INOUT parameter's value is read through OutputParameters.

Return values. ReturnValue is populated only where the provider supports a procedure return status (SQL Server, through a ReturnValue parameter). MySQL and PostgreSQL have no such return value.

Capability. SQL Server, PostgreSQL and MySQL/MariaDB support this call; SQLite, ClickHouse and the in-memory context throw NotSupportedException.

Exceptions

ArgumentException

name is null, empty or whitespace.

ArgumentNullException

parameters is null.

NotSupportedException

The provider has no stored procedures (ISqlDialect.SupportsStoredProcedures is false).

ExecuteProcedureAsync(string, params IReadOnlyList<ProcedureParameter>)

Asynchronously executes the stored procedure name with parameters, using None. Convenience overload of ExecuteProcedureAsync(string, IReadOnlyList<ProcedureParameter>, CancellationToken) for callers whose static type is the concrete context.

public Task<ProcedureResult> ExecuteProcedureAsync(string name, params IReadOnlyList<ProcedureParameter> parameters)

Parameters

name string

The procedure name, passed to the provider as-is.

parameters IReadOnlyList<ProcedureParameter>

The procedure parameters (input, output, input/output and return value).

Returns

Task<ProcedureResult>

A task producing the result, which must be disposed to release the reader and command.

ExecuteProcedureAsync(string, IReadOnlyList<ProcedureParameter>, CancellationToken)

Asynchronously executes the stored procedure name with parameters and returns a ProcedureResult owning the reader and command. See ExecuteProcedure(string, params IReadOnlyList<ProcedureParameter>) for the name, PostgreSQL and return-value notes.

public Task<ProcedureResult> ExecuteProcedureAsync(string name, IReadOnlyList<ProcedureParameter> parameters, CancellationToken cancellationToken = default)

Parameters

name string

The procedure name, passed to the provider as-is.

parameters IReadOnlyList<ProcedureParameter>

The procedure parameters (input, output, input/output and return value).

cancellationToken CancellationToken

Cancels execution.

Returns

Task<ProcedureResult>

A task producing the result, which must be disposed to release the reader and command.

Exceptions

ArgumentException

name is null, empty or whitespace.

ArgumentNullException

parameters is null.

NotSupportedException

The provider has no stored procedures (ISqlDialect.SupportsStoredProcedures is false).

ExecuteRaw(string, params IReadOnlyList<ProcedureParameter>)

Executes sql with parameters and returns a ProcedureResult owning the reader and command.

public ProcedureResult ExecuteRaw(string sql, params IReadOnlyList<ProcedureParameter> parameters)

Parameters

sql string

The command text to execute.

parameters IReadOnlyList<ProcedureParameter>

The parameters referenced by sql.

Returns

ProcedureResult

The result, which must be disposed to release the reader and command.

Remarks

SQL injection. sql is sent to the provider verbatim and never parameterised by the planner. Never concatenate untrusted input into it; pass values through ProcedureParameter so the provider binds them.

Open reader. The returned ProcedureResult holds the command and its reader open until disposed. On SQL Server without MARS, an open reader blocks every other command on the same connection — dispose the result (and read/close it) before issuing another command on the context. On providers that support multiple active result sets this is provider-dependent.

Return values. A ReturnValue parameter is populated only for a stored-procedure command type issued through ExecuteProcedure(string, params IReadOnlyList<ProcedureParameter>), and only where the provider has a return status (SQL Server). Text commands like EXEC are provider-dependent and typically leave it unset; capture a value with an Output parameter instead.

Mapping. Read<T>() accepts a scalar or a mapped entity. A mapped entity's metadata is resolved from Metadata or, when absent, registered on demand with the default mapping (attributes and auto-derived names, the context's naming convention applied). A scalar read of SQL NULL returns default; use a nullable T (for example int?) to observe a NULL.

ExecuteRawAsync(string, params IReadOnlyList<ProcedureParameter>)

Asynchronously executes sql with parameters, using None. Convenience overload of ExecuteRawAsync(string, IReadOnlyList<ProcedureParameter>, CancellationToken) for callers whose static type is the concrete context.

public Task<ProcedureResult> ExecuteRawAsync(string sql, params IReadOnlyList<ProcedureParameter> parameters)

Parameters

sql string

The command text to execute.

parameters IReadOnlyList<ProcedureParameter>

The parameters referenced by sql.

Returns

Task<ProcedureResult>

A task producing the result, which must be disposed to release the reader and command.

ExecuteRawAsync(string, IReadOnlyList<ProcedureParameter>, CancellationToken)

Asynchronously executes sql with parameters and returns a ProcedureResult owning the reader and command. See ExecuteRaw(string, params IReadOnlyList<ProcedureParameter>) for the SQL-injection, open reader (MARS) and return-value notes.

public Task<ProcedureResult> ExecuteRawAsync(string sql, IReadOnlyList<ProcedureParameter> parameters, CancellationToken cancellationToken = default)

Parameters

sql string

The command text to execute.

parameters IReadOnlyList<ProcedureParameter>

The parameters referenced by sql.

cancellationToken CancellationToken

Cancels execution.

Returns

Task<ProcedureResult>

A task producing the result, which must be disposed to release the reader and command.

ExecuteScalar<TResult>(IPreparedQueryCommand<TResult>, object[]?, bool, CancellationToken)

Executes the command and converts the first column of the first row to TResult.

public Task<TResult?> ExecuteScalar<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, bool throwIfNull, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params object[]

Positional parameters bound to the command, or null.

throwIfNull bool

When true, throws InvalidOperationException when the result is null or DBNull; otherwise returns default.

cancellationToken CancellationToken

Token used to cancel execution.

Returns

Task<TResult>

The scalar value, or default when the result is null and throwIfNull is false.

Type Parameters

TResult

The scalar type to convert the value to.

ExecuteScalar<TResult>(IPreparedQueryCommand<TResult>, ReadOnlySpan<object?>, bool)

Executes the command and converts the first column of the first row to TResult.

public TResult? ExecuteScalar<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, ReadOnlySpan<object?> @params, bool throwIfNull)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params ReadOnlySpan<object>

Positional parameters bound to the command.

throwIfNull bool

When true, throws InvalidOperationException when the result is null or DBNull; otherwise returns default.

Returns

TResult

The scalar value, or default when the result is null and throwIfNull is false.

Type Parameters

TResult

The scalar type to convert the value to.

FirstAsync<TResult>(IPreparedQueryCommand<TResult>, object[]?, CancellationToken)

Asynchronously returns the first row of the result.

public Task<TResult> FirstAsync<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params object[]

Positional parameters bound to the command, or null.

cancellationToken CancellationToken

Token used to cancel execution.

Returns

Task<TResult>

The first projected row.

Type Parameters

TResult

The projected result type.

Exceptions

InvalidOperationException

The result set is empty.

FirstOrDefaultAsync<TResult>(IPreparedQueryCommand<TResult>, object[]?, CancellationToken)

Asynchronously returns the first row of the result, or default when the result set is empty.

public Task<TResult?> FirstOrDefaultAsync<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params object[]

Positional parameters bound to the command, or null.

cancellationToken CancellationToken

Token used to cancel execution.

Returns

Task<TResult>

The first projected row, or default when there is none.

Type Parameters

TResult

The projected result type.

FirstOrDefault<TResult>(IPreparedQueryCommand<TResult>, ReadOnlySpan<object?>)

Returns the first row of the result, or default when the result set is empty.

public TResult? FirstOrDefault<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, ReadOnlySpan<object?> @params)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params ReadOnlySpan<object>

Positional parameters bound to the command.

Returns

TResult

The first projected row, or default when there is none.

Type Parameters

TResult

The projected result type.

First<TResult>(IPreparedQueryCommand<TResult>, ReadOnlySpan<object?>)

Returns the first row of the result.

public TResult First<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, ReadOnlySpan<object?> @params)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params ReadOnlySpan<object>

Positional parameters bound to the command.

Returns

TResult

The first projected row.

Type Parameters

TResult

The projected result type.

Exceptions

InvalidOperationException

The result set is empty.

From(string)

Starts a query over the raw physical table named table.

public EntityBuilder From(string table)

Parameters

table string

The physical table name to select from.

Returns

EntityBuilder

A builder over the table.

Exceptions

ArgumentNullException

table is null.

ArgumentException

table is empty or consists only of white-space characters.

GetConnection()

Returns the connection in use, creating it on first access (which may throw if the connection string is missing).

public DbConnection GetConnection()

Returns

DbConnection

The underlying database connection.

GetFrom(Type, QueryCommand?)

Resolves the FROM source for srcType, reusing the source carried by queryCommand when present.

public FromExpression? GetFrom(Type srcType, QueryCommand? queryCommand)

Parameters

srcType Type

The entity or source type to resolve.

queryCommand QueryCommand

The derived command whose source should be used, or null.

Returns

FromExpression

The resolved FROM expression, or null when the type is not mapped.

GetPreparedQueryCommand<TResult>(QueryCommand<TResult>, bool, bool, PreparedCommandCache, CancellationToken)

Prepares queryCommand against the current dialect with an explicit command-reuse policy, optionally building a streaming enumerator and storing the plan in the cache.

public IPreparedQueryCommand<TResult> GetPreparedQueryCommand<TResult>(QueryCommand<TResult> queryCommand, bool createEnumerator, bool storeInCache, PreparedCommandCache cache, CancellationToken cancellationToken)

Parameters

queryCommand QueryCommand<TResult>

The command to prepare.

createEnumerator bool

When true, compiles a streaming row enumerator as part of preparation.

storeInCache bool

When true (and QueryCacheEnabled is set), stores the prepared command in the plan cache.

cache PreparedCommandCache

The command-reuse policy the prepared command is built with.

cancellationToken CancellationToken

Token used to cancel preparation.

Returns

IPreparedQueryCommand<TResult>

The prepared command, ready to execute.

Type Parameters

TResult

The projected result type.

GetPreparedQueryCommand<TResult>(QueryCommand<TResult>, bool, bool, CancellationToken)

Prepares queryCommand against the current dialect, optionally building a streaming enumerator and storing the plan in the cache. When storeInCache is set, later calls return the cached plan instead of re-planning.

public IPreparedQueryCommand<TResult> GetPreparedQueryCommand<TResult>(QueryCommand<TResult> queryCommand, bool createEnumerator, bool storeInCache, CancellationToken cancellationToken)

Parameters

queryCommand QueryCommand<TResult>

The command to prepare.

createEnumerator bool

When true, compiles a streaming row enumerator as part of preparation.

storeInCache bool

When true (and QueryCacheEnabled is set), stores the prepared command in the plan cache.

cancellationToken CancellationToken

Token used to cancel preparation.

Returns

IPreparedQueryCommand<TResult>

The prepared command, ready to execute.

Type Parameters

TResult

The projected result type.

IsGenuineCompositeColumn(DbDataReader, int)

Reports whether the provider authoritatively identifies the reader column at ordinal as a genuine composite (a PostgreSQL named or struct composite) rather than a scalar or a provider struct. The default is false: without authoritative metadata no column is classified as a composite, so a dotted data type name or a metadata-probe exception never produces a composite verdict. The raw-row mapper consults this as its sole composite-identification source.

protected virtual bool IsGenuineCompositeColumn(DbDataReader reader, int ordinal)

Parameters

reader DbDataReader

The reader whose current result set is being classified.

ordinal int

The zero-based column ordinal.

Returns

bool

true when the provider identifies the column as a genuine composite.

MapColumnExpression(SelectExpression, Expression)

Maps a projected column to a reader accessor. Providers whose reader does not widen CLR types (SqlClient throws when a typed getter does not match the field type, for example an int column projected as long) can override this to read the value and convert it.

public virtual Expression MapColumnExpression(SelectExpression column, Expression param)

Parameters

column SelectExpression
param Expression

Returns

Expression

MapTypedColumnExpression(SelectExpression, Expression, Type)

Maps a projected column when the reader's actual field (storage) type is known. The CSV terminal calls this after the reader is open, passing reader.GetFieldType(column.Index), so a provider can pick a typed getter for the storage type and convert to the projected type without going through GetValue(int). It is a provider extension point: protected so it does not widen the context's public surface, and overridden by providers (for example SqlServerDataContext) whose reader does not widen numerics. The default ignores storageType and delegates to MapColumnExpression(SelectExpression, Expression) so buffered materialization is unchanged.

protected virtual Expression MapTypedColumnExpression(SelectExpression column, Expression record, Type storageType)

Parameters

column SelectExpression

The projected column being read.

record Expression

The data-reader expression the accessor is built from.

storageType Type

The reader's CLR field type for the column's ordinal.

Returns

Expression

An expression that reads (and, when needed, converts) the column value.

OnConnectionCreated(DbConnection)

Called for every connection the context starts using (created or supplied) so a provider can run provider-specific setup, e.g. registering custom functions.

protected virtual void OnConnectionCreated(DbConnection connection)

Parameters

connection DbConnection

PurgeQueryCache()

Clears all cached query plans held by this context.

public void PurgeQueryCache()

ResetPreparation(QueryCommand)

Resets the cached execution plan of queryCommand so it is rebuilt on next use.

public void ResetPreparation(QueryCommand queryCommand)

Parameters

queryCommand QueryCommand

The command whose plan should be discarded.

SingleAsync<TResult>(IPreparedQueryCommand<TResult>, object[]?, CancellationToken)

Asynchronously returns the only row of the result.

public Task<TResult> SingleAsync<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params object[]

Positional parameters bound to the command, or null.

cancellationToken CancellationToken

Token used to cancel execution.

Returns

Task<TResult>

The single projected row.

Type Parameters

TResult

The projected result type.

Exceptions

InvalidOperationException

The result set is empty or contains more than one row.

SingleOrDefaultAsync<TResult>(IPreparedQueryCommand<TResult>, object[]?, CancellationToken)

Asynchronously returns the only row of the result, or default when the result set is empty.

public Task<TResult?> SingleOrDefaultAsync<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params object[]

Positional parameters bound to the command, or null.

cancellationToken CancellationToken

Token used to cancel execution.

Returns

Task<TResult>

The single projected row, or default when there is none.

Type Parameters

TResult

The projected result type.

Exceptions

InvalidOperationException

The result set contains more than one row.

SingleOrDefault<TResult>(IPreparedQueryCommand<TResult>, ReadOnlySpan<object?>)

Returns the only row of the result, or default when the result set is empty.

public TResult? SingleOrDefault<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, ReadOnlySpan<object?> @params)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params ReadOnlySpan<object>

Positional parameters bound to the command.

Returns

TResult

The single projected row, or default when there is none.

Type Parameters

TResult

The projected result type.

Exceptions

InvalidOperationException

The result set contains more than one row.

Single<TResult>(IPreparedQueryCommand<TResult>, ReadOnlySpan<object?>)

Returns the only row of the result.

public TResult Single<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, ReadOnlySpan<object?> @params)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params ReadOnlySpan<object>

Positional parameters bound to the command.

Returns

TResult

The single projected row.

Type Parameters

TResult

The projected result type.

Exceptions

InvalidOperationException

The result set is empty or contains more than one row.

SupportsTypedColumnMapping(SelectExpression)

True when MapTypedColumnExpression(SelectExpression, Expression, Type) will read column through a typed getter even though MapColumnExpression(SelectExpression, Expression) (which has no storage type to work with) would box through GetValue(int)/Convert.ChangeType(object). The CSV terminal calls this before the query is executed, when only the static projection is known, so it can reject a column that will box on every row without falsely rejecting a provider whose typed hook is storage-driven (SQL Server numeric widening). The default is false.

protected virtual bool SupportsTypedColumnMapping(SelectExpression column)

Parameters

column SelectExpression

The projected column about to be validated.

Returns

bool

true when the typed hook can bind the column box-free.

ToListAsync<TResult>(IPreparedQueryCommand<TResult>, object[]?, CancellationToken)

Executes the command and buffers all rows into a list.

public Task<List<TResult>> ToListAsync<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, object[]? @params, CancellationToken cancellationToken)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params object[]

Positional parameters bound to the command, or null.

cancellationToken CancellationToken

Token used to cancel execution.

Returns

Task<List<TResult>>

The materialised rows; empty when the query yields none.

Type Parameters

TResult

The projected result type.

ToList<TResult>(IPreparedQueryCommand<TResult>, ReadOnlySpan<object?>)

Executes the command and buffers all rows into a list.

public List<TResult> ToList<TResult>(IPreparedQueryCommand<TResult> preparedQueryCommand, ReadOnlySpan<object?> @params)

Parameters

preparedQueryCommand IPreparedQueryCommand<TResult>

The prepared command to execute.

params ReadOnlySpan<object>

Positional parameters bound to the command.

Returns

List<TResult>

The materialised rows; empty when the query yields none.

Type Parameters

TResult

The projected result type.

Events

Disposed

Raised after the context has released its connection during disposal.

public event EventHandler? Disposed

Event Type

EventHandler