Table of Contents

Class SqlServerDataContext

Namespace
NextORM.SqlServer
Assembly
nextorm.sqlserver.dll

Data context for Microsoft SQL Server. Wraps the Microsoft.Data.SqlClient driver for connections and parameters and renders SQL through SqlServerDialect.

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

Constructors

SqlServerDataContext(SqlServerEngineEdition, DbConnection)

Creates a SQL Server context that declares its engine edition over a caller-supplied connection, which the context does not dispose. The declaration is the only input to the edition-derived capabilities; nothing is probed.

public SqlServerDataContext(SqlServerEngineEdition engineEdition, DbConnection connection)

Parameters

engineEdition SqlServerEngineEdition

The engine edition this context declares.

connection DbConnection

An already-created DbConnection owned by the caller.

Exceptions

ArgumentOutOfRangeException

engineEdition is not a defined SqlServerEngineEdition value.

InvalidOperationException

A different capability declaration was already registered for this context type.

SqlServerDataContext(SqlServerEngineEdition, string)

Creates a SQL Server context that declares its engine edition and owns a connection built lazily from connectionString. The declaration is the only input to the edition-derived capabilities — for example an Azure SQL Database or Managed Instance deployment, which reports ProductMajorVersion 12 while its engine has the native json type. No server property is read, so the emitted SQL is fixed by the declaration.

public SqlServerDataContext(SqlServerEngineEdition engineEdition, string connectionString)

Parameters

engineEdition SqlServerEngineEdition

The engine edition this context declares.

connectionString string

The connection string used to create the SqlConnection.

Exceptions

ArgumentOutOfRangeException

engineEdition is not a defined SqlServerEngineEdition value.

InvalidOperationException

A different capability declaration was already registered for this context type.

SqlServerDataContext(DbConnection, DataContextBuilder)

Creates a SQL Server context over a caller-supplied connection, which the context does not dispose. The context is unversioned: every version-dependent capability keeps its historical value.

public SqlServerDataContext(DbConnection connection, DataContextBuilder optionsBuilder)

Parameters

connection DbConnection

An already-created DbConnection owned by the caller.

optionsBuilder DataContextBuilder

The options collected from DataContextBuilder.

SqlServerDataContext(string, DataContextBuilder)

Creates a SQL Server context that owns a connection built lazily from connectionString. The context is unversioned: every version-dependent capability keeps its historical value.

public SqlServerDataContext(string connectionString, DataContextBuilder optionsBuilder)

Parameters

connectionString string

The connection string used to create the SqlConnection.

optionsBuilder DataContextBuilder

The options collected from DataContextBuilder.

SqlServerDataContext(Version, SqlServerEngineEdition, DbConnection)

Creates a SQL Server context bound to an explicitly declared server version and engine edition over a caller-supplied connection, which the context does not dispose.

public SqlServerDataContext(Version serverVersion, SqlServerEngineEdition engineEdition, DbConnection connection)

Parameters

serverVersion Version

The SQL Server version this context declares.

engineEdition SqlServerEngineEdition

The engine edition this context declares.

connection DbConnection

An already-created DbConnection owned by the caller.

Exceptions

ArgumentNullException

serverVersion is null; use the edition-only constructor instead.

ArgumentOutOfRangeException

engineEdition is not a defined SqlServerEngineEdition value.

InvalidOperationException

A different capability declaration was already registered for this context type.

SqlServerDataContext(Version, SqlServerEngineEdition, string)

Creates a SQL Server context bound to an explicitly declared server version and engine edition that owns a connection built lazily from connectionString. Both values are caller declarations; the version gate and the edition allowlist are evaluated over them alone.

public SqlServerDataContext(Version serverVersion, SqlServerEngineEdition engineEdition, string connectionString)

Parameters

serverVersion Version

The SQL Server version this context declares.

engineEdition SqlServerEngineEdition

The engine edition this context declares.

connectionString string

The connection string used to create the SqlConnection.

Exceptions

ArgumentNullException

serverVersion is null; use the edition-only constructor instead.

ArgumentOutOfRangeException

engineEdition is not a defined SqlServerEngineEdition value.

InvalidOperationException

A different capability declaration was already registered for this context type.

SqlServerDataContext(Version, DbConnection)

Creates a SQL Server context bound to an explicitly declared server version over a caller-supplied connection, which the context does not dispose.

public SqlServerDataContext(Version serverVersion, DbConnection connection)

Parameters

serverVersion Version

The SQL Server version this context declares.

connection DbConnection

An already-created DbConnection owned by the caller.

Exceptions

ArgumentNullException

serverVersion is null; use the unversioned constructor instead.

InvalidOperationException

A different server version was already registered for this context type.

SqlServerDataContext(Version, string)

Creates a SQL Server context bound to an explicitly declared server version that owns a connection built lazily from connectionString. The declared version decides the version-gated capabilities (for example native json storage, which needs major 17); the server itself is never queried for it.

public SqlServerDataContext(Version serverVersion, string connectionString)

Parameters

serverVersion Version

The SQL Server version this context declares.

connectionString string

The connection string used to create the SqlConnection.

Exceptions

ArgumentNullException

serverVersion is null; use the unversioned constructor instead.

InvalidOperationException

A different server version was already registered for this context type.

Properties

Dialect

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

public override ISqlDialect Dialect { get; }

Property Value

ISqlDialect

TimeOnlyProjectionRefusal

SQL Server time is a true time of day and SqlClient surfaces it as TimeSpan with 100 ns precision, so the projection is supported.

protected override string? TimeOnlyProjectionRefusal { get; }

Property Value

string

Methods

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

Compatibility entry point for the base hook: writes rows through SqlBulkCopy with the budget expressed in whole seconds. The executor path above carries the full TimeSpan budget and the SQL Server option group; this hook never requests an internal transaction.

protected override 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.

rows IEnumerable<object[]>

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

commandTimeoutSeconds int?

The Timeout budget in whole seconds, or null for the 30s default.

maxBatchSize int?

The SqlBulkCopy.BatchSize in rows, or null for the driver default (0).

progress Action<int>

Called with the cumulative written-row count on each native progress tick, or null.

notifyEvery int

The progress reporting interval in rows.

bulkCopy BulkCopyFlags

The bulk-copy flags requested by the caller.

Returns

int

The number of rows written.

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

Asynchronously writes rows through SqlBulkCopy.

protected override 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.

rows IAsyncEnumerable<object[]>

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

commandTimeoutSeconds int?

The Timeout budget in whole seconds, or null for the 30s default.

maxBatchSize int?

The SqlBulkCopy.BatchSize in rows, or null for the driver default (0).

progress Action<int>

Called with the cumulative written-row count on each native progress tick, or null.

notifyEvery int

The progress reporting interval in rows.

bulkCopy BulkCopyFlags

The bulk-copy flags requested by the caller.

cancellationToken CancellationToken

Cancels execution.

Returns

Task<int>

A task producing the number of rows written.

CreateDbConnection(string?)

Creates a new SqlConnection for connectionString.

protected override DbConnection CreateDbConnection(string? connectionString)

Parameters

connectionString string

The SQL Server connection string.

Returns

DbConnection

A new, unopened SQL Server connection.

CreateParam(string, object?)

Creates a SqlParameter, mapping a null value to DBNull.Value because SqlClient otherwise omits the parameter entirely.

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

Parameters

name string

The parameter name, without the provider prefix.

value object

The parameter value, or null.

Returns

DbParameter

A new SQL Server parameter.

CreateProcedureParameter(ProcedureParameter)

Creates a SqlParameter from a descriptor, additionally applying a structured parameter type name. When TypeName is set the parameter is marked Structured (SqlClient rejects a type name on a non-structured parameter) — a structured parameter is input only, so any other ParameterDirection is rejected. Structured overrides DbType for that parameter; the legacy value must be a DataTable/IEnumerable<SqlDataRecord>.

When Value is a TableParameterValue (built with Table<T>(string, string, IEnumerable<T>)) the rows are streamed as SqlDataRecords and TypeName is required.

The CLR type of each bound column picks a fixed T-SQL type: bool→bit, char→nchar(1), sbyte/short→smallint, byte→tinyint, ushort/int→int, uint/long→bigint, ulong→decimal(20,0), float→real, double→float, decimal→decimal(38,18) (or the property's declared precision/scale), string→nvarchar(max), Guid→uniqueidentifier, DateTime→datetime2, DateTimeOffset→datetimeoffset, DateOnly→date, TimeOnly→time, TimeSpan→bigint (the mapped duration unit, or ticks) and byte[]→varbinary(max). A decimal column uses the precision/scale declared with DecimalPrecisionAttribute or the fluent mapping, defaulting to decimal(38,18); for a different precision/scale on any other type declare the user-defined table type explicitly and pass a legacy DataTable with TypeName.

protected override DbParameter CreateProcedureParameter(ProcedureParameter parameter)

Parameters

parameter ProcedureParameter

The parameter descriptor.

Returns

DbParameter

A new SQL Server parameter configured from parameter.

Exceptions

ArgumentException

parameter is a table-valued parameter without a type name, or a structured parameter whose ParameterDirection is not Input.

MapColumnExpression(SelectExpression, Expression)

Maps projected numeric columns by reading the raw value and converting it to the projected CLR type, because SqlClient typed getters throw when the field type does not match. A TimeSpan projection is dispatched per row between a native time field and an integer-backed duration.

public override Expression MapColumnExpression(SelectExpression column, Expression param)

Parameters

column SelectExpression

The projected column being read.

param Expression

The data-reader expression the accessor is built from.

Returns

Expression

An expression that reads and converts the column value.

MapTypedColumnExpression(SelectExpression, Expression, Type)

CSV-terminal variant of MapColumnExpression(SelectExpression, Expression): for an unconverted numeric column it reads the value with the typed getter of the reader's actual storage type (storageType) and converts it with the matching static Convert.To<Target>(storage) overload. It shares the getter/conversion lookup with the buffered mapper (MapColumnExpression(SelectExpression, Expression)), which resolves the same pairing from the runtime GetFieldType(int).

protected override 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 converts the column value without boxing.

SupportsTypedColumnMapping(SelectExpression)

The typed CSV hook reads an unconverted numeric column with the storage-typed getter of the reader's actual field type, so a numeric column that MapColumnExpression(SelectExpression, Expression) would widen through GetValue must not be rejected before the reader reports its storage type. A converted column keeps its converter and a non-numeric column is not handled by the typed hook, so both keep the default rejection.

protected override bool SupportsTypedColumnMapping(SelectExpression column)

Parameters

column SelectExpression

Returns

bool