Class DataContext
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
optionsBuilderDataContextBuilderThe 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
connectionStringstringConnection string used to create a context-owned connection, or null.
providedConnectionDbConnectionAn already-created connection owned by the caller, or null.
optionsBuilderDataContextBuilderThe 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
connectionStringstringConnection string used to create a context-owned connection, or null.
providedConnectionDbConnectionAn already-created connection owned by the caller, or null.
optionsBuilderDataContextBuilderThe options collected from
DataContextBuilder.serverVersionVersionThe 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
CommandLogger
Logger category used to trace executed commands and their parameters.
public ILogger? CommandLogger { get; }
Property Value
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
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
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
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
LogSensitiveData
Whether sensitive parameter values may be logged. Kept for provider subclasses.
protected bool LogSensitiveData { get; }
Property Value
Logger
Logger for the context's own diagnostic messages, or null when no logger factory was configured.
public ILogger? Logger { get; }
Property Value
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
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
NeedMapping
Whether projected rows must be materialised into CLR objects.
public bool NeedMapping { get; }
Property Value
Properties
User-owned bag of arbitrary state attached to this context.
public Dictionary<string, object> Properties { get; }
Property Value
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
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
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
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
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
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
interceptorIConnectionInterceptorThe interceptor to register; must not be null.
Exceptions
- ArgumentNullException
interceptoris 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
interceptorIQueryInterceptorThe interceptor to register; must not be null.
Exceptions
- ArgumentNullException
interceptoris 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
dbParameterDbParameterThe provider parameter to configure.
parameterProcedureParameterThe descriptor carrying the metadata.
Returns
- DbParameter
dbParameter, configured fromparameter.
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
tableNamestringThe rendered target table reference (schema-qualified, quoted when configured).
columnNamesIReadOnlyList<string>The convention-resolved (unquoted) written column names, in row order.
columnsIReadOnlyList<IPropertyMetadata>The mapped columns, in row order (for CLR types and identity flags).
rowsIEnumerable<object[]>The rows to write; each array matches
columnNamesby ordinal.commandTimeoutSecondsint?The command timeout in seconds, or null for the provider default.
maxBatchSizeint?The maximum rows per batch, or null for the provider default.
progressAction<int>The progress callback, called with the cumulative written-row count, or null.
notifyEveryintThe progress reporting interval in rows; the provider drives its cadence from it.
bulkCopyBulkCopyFlagsThe 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
tableNamestringThe rendered target table reference (schema-qualified, quoted when configured).
columnNamesIReadOnlyList<string>The convention-resolved (unquoted) written column names, in row order.
columnsIReadOnlyList<IPropertyMetadata>The mapped columns, in row order (for CLR types and identity flags).
rowsIAsyncEnumerable<object[]>The rows to write; each array matches
columnNamesby ordinal.commandTimeoutSecondsint?The command timeout in seconds, or null for the provider default.
maxBatchSizeint?The maximum rows per batch, or null for the provider default.
progressAction<int>The progress callback, called with the cumulative written-row count, or null.
notifyEveryintThe progress reporting interval in rows; the provider drives its cadence from it.
bulkCopyBulkCopyFlagsThe bulk-copy flags requested by the caller; only the provider's native path can express them.
cancellationTokenCancellationTokenCancels execution.
Returns
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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to enumerate.
paramsobject[]Positional parameters bound to the command, or null.
cancellationTokenCancellationTokenToken used to cancel enumeration.
Returns
- IAsyncEnumerator<TResult>
An async enumerator over the result rows.
Type Parameters
TResultThe 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
sqlstringThe 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
connectionStringstring
Returns
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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to enumerate.
paramsobject[]Positional parameters bound to the command, or null.
Returns
- IEnumerator<TResult>
A synchronous enumerator over the result rows.
Type Parameters
TResultThe 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
commandDbCommandThe executing command the parameter will be added to.
namestringThe parameter name, without the provider's prefix.
valueobjectThe 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
namestringThe parameter name, without the provider's prefix.
valueobjectThe 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
parameterProcedureParameterThe parameter descriptor.
Returns
- DbParameter
A new database parameter configured from
parameter.
Exceptions
- ArgumentException
- 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
commandDbCommandThe executing command the parameter will be added to.
parameterProcedureParameterThe parameter descriptor.
Returns
- DbParameter
A new database parameter configured from
parameter.
Exceptions
- ArgumentException
- 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
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
cancellationTokenCancellationTokenToken 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
namestringThe procedure name, passed to the provider as-is.
parametersIReadOnlyList<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
nameis null, empty or whitespace.- ArgumentNullException
parametersis null.- NotSupportedException
The provider has no stored procedures (
ISqlDialect.SupportsStoredProceduresisfalse).
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
namestringThe procedure name, passed to the provider as-is.
parametersIReadOnlyList<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
namestringThe procedure name, passed to the provider as-is.
parametersIReadOnlyList<ProcedureParameter>The procedure parameters (input, output, input/output and return value).
cancellationTokenCancellationTokenCancels execution.
Returns
- Task<ProcedureResult>
A task producing the result, which must be disposed to release the reader and command.
Exceptions
- ArgumentException
nameis null, empty or whitespace.- ArgumentNullException
parametersis null.- NotSupportedException
The provider has no stored procedures (
ISqlDialect.SupportsStoredProceduresisfalse).
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
sqlstringThe command text to execute.
parametersIReadOnlyList<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
sqlstringThe command text to execute.
parametersIReadOnlyList<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
sqlstringThe command text to execute.
parametersIReadOnlyList<ProcedureParameter>The parameters referenced by
sql.cancellationTokenCancellationTokenCancels 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsobject[]Positional parameters bound to the command, or null.
throwIfNullboolWhen true, throws InvalidOperationException when the result is null or
DBNull; otherwise returns default.cancellationTokenCancellationTokenToken used to cancel execution.
Returns
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsReadOnlySpan<object>Positional parameters bound to the command.
throwIfNullboolWhen true, throws InvalidOperationException when the result is null or
DBNull; otherwise returns default.
Returns
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsobject[]Positional parameters bound to the command, or null.
cancellationTokenCancellationTokenToken used to cancel execution.
Returns
- Task<TResult>
The first projected row.
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsobject[]Positional parameters bound to the command, or null.
cancellationTokenCancellationTokenToken used to cancel execution.
Returns
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsReadOnlySpan<object>Positional parameters bound to the command.
Returns
- TResult
The first projected row, or default when there is none.
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsReadOnlySpan<object>Positional parameters bound to the command.
Returns
- TResult
The first projected row.
Type Parameters
TResultThe 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
tablestringThe physical table name to select from.
Returns
- EntityBuilder
A builder over the table.
Exceptions
- ArgumentNullException
tableis null.- ArgumentException
tableis 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
srcTypeTypeThe entity or source type to resolve.
queryCommandQueryCommandThe 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
queryCommandQueryCommand<TResult>The command to prepare.
createEnumeratorboolWhen true, compiles a streaming row enumerator as part of preparation.
storeInCacheboolWhen true (and QueryCacheEnabled is set), stores the prepared command in the plan cache.
cachePreparedCommandCacheThe command-reuse policy the prepared command is built with.
cancellationTokenCancellationTokenToken used to cancel preparation.
Returns
- IPreparedQueryCommand<TResult>
The prepared command, ready to execute.
Type Parameters
TResultThe 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
queryCommandQueryCommand<TResult>The command to prepare.
createEnumeratorboolWhen true, compiles a streaming row enumerator as part of preparation.
storeInCacheboolWhen true (and QueryCacheEnabled is set), stores the prepared command in the plan cache.
cancellationTokenCancellationTokenToken used to cancel preparation.
Returns
- IPreparedQueryCommand<TResult>
The prepared command, ready to execute.
Type Parameters
TResultThe 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
readerDbDataReaderThe reader whose current result set is being classified.
ordinalintThe zero-based column ordinal.
Returns
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
columnSelectExpressionparamExpression
Returns
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
columnSelectExpressionThe projected column being read.
recordExpressionThe data-reader expression the accessor is built from.
storageTypeTypeThe 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
connectionDbConnection
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
queryCommandQueryCommandThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsobject[]Positional parameters bound to the command, or null.
cancellationTokenCancellationTokenToken used to cancel execution.
Returns
- Task<TResult>
The single projected row.
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsobject[]Positional parameters bound to the command, or null.
cancellationTokenCancellationTokenToken used to cancel execution.
Returns
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsReadOnlySpan<object>Positional parameters bound to the command.
Returns
- TResult
The single projected row, or default when there is none.
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsReadOnlySpan<object>Positional parameters bound to the command.
Returns
- TResult
The single projected row.
Type Parameters
TResultThe 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
columnSelectExpressionThe projected column about to be validated.
Returns
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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsobject[]Positional parameters bound to the command, or null.
cancellationTokenCancellationTokenToken used to cancel execution.
Returns
Type Parameters
TResultThe 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
preparedQueryCommandIPreparedQueryCommand<TResult>The prepared command to execute.
paramsReadOnlySpan<object>Positional parameters bound to the command.
Returns
- List<TResult>
The materialised rows; empty when the query yields none.
Type Parameters
TResultThe projected result type.
Events
Disposed
Raised after the context has released its connection during disposal.
public event EventHandler? Disposed