Class DataContextBuilder
Configures and creates an IDataContext.
public class DataContextBuilder
- Inheritance
-
DataContextBuilder
- Inherited Members
- Extension Methods
Remarks
The DataContext prefix is inconsistent with the rest of the library, which otherwise uses
DataContext (for example DataContextOptionsBuilderExtensions). Recommended name:
DataContextBuilder. See docs/specs/design/API-NAMING-REVIEW.md finding P2-22.
Constructors
DataContextBuilder()
Creates a standalone builder whose interceptors must be supplied as instances.
public DataContextBuilder()
Properties
CommandTimeout
The command timeout in seconds applied to every command of the contexts this builder creates, or
null when no timeout is configured and the provider default applies. Set through
UseCommandTimeout(int); a command can override it with WithCommandTimeout.
public int? CommandTimeout { get; }
Property Value
- int?
EagerLoadMode
The context-wide default eager-load strategy applied to LoadWith collections when a query
declares no explicit mode. Defaults to SplitQuery (the historical
behavior); set through UseEagerLoadMode(EagerLoadMode). A query override
(LoadWith(..., mode)) always wins over this default, and configuring a context never
changes a static/global value.
public EagerLoadMode EagerLoadMode { get; }
Property Value
Factory
Factory invoked by CreateDataContext() to materialize the configured context.
null until one of the provider extensions (for example
UseInMemoryContext) assigns it; CreateDataContext() throws
InvalidOperationException in that state.
public Func<DataContextBuilder, IDataContext>? Factory { get; set; }
Property Value
KeywordCase
The letter case in which SQL keywords are emitted by default. Defaults to
Lower (unchanged historical output); can be overridden per
command with WithKeywordCase. Set through UseKeywordCase(KeywordCase).
public KeywordCase KeywordCase { get; }
Property Value
MultilineBatchSql
Whether a rendered batch places each statement on its own line. Defaults to
false (statements joined on one line with "; "). Set through
UseMultilineBatchSql(bool); affects the batch SQL produced by BatchQuery.ToSql()
and the joined command text only, not the per-command DbBatch form.
public bool MultilineBatchSql { get; }
Property Value
NamingConvention
Convention applied by default to table and column names that were not declared explicitly
(no attribute/fluent mapping). null (the default) emits the CLR names
verbatim; can be overridden per command with WithNamingConvention.
public INamingConvention? NamingConvention { get; }
Property Value
QueryCacheEnabled
Whether prepared queries may be stored in and reused from the plan cache. Defaults to
true; set through UseQueryCache(bool). When disabled, every
preparation is built without caching (the equivalent of storeInCache: false) and the
per-command QueryCommand.Cache flag is never mutated.
public bool QueryCacheEnabled { get; }
Property Value
QuoteIdentifiers
Whether physical identifiers (table and column names) are quoted with the provider's delimiter
in generated SQL. Defaults to false (names are emitted verbatim); can be overridden per
command with WithQuotedIdentifiers.
public bool QuoteIdentifiers { get; }
Property Value
ShouldLogSensitiveData
Whether command parameter values are written to the configured logger. Defaults to false; enable it only for local diagnostics, since parameter values may contain sensitive data. Set through LogSensitiveData(bool).
public bool ShouldLogSensitiveData { get; }
Property Value
Methods
AddInterceptor(IConnectionInterceptor)
Registers a connection interceptor that observes the connection lifecycle of every context this builder creates. Interceptors are invoked in registration order, after the ones already registered.
public DataContextBuilder AddInterceptor(IConnectionInterceptor interceptor)
Parameters
interceptorIConnectionInterceptorThe interceptor to register; must not be null.
Returns
- DataContextBuilder
This builder, to allow chaining.
Remarks
An instance that also implements IQueryInterceptor is attached to both event pipelines. Registration is deduplicated by the instance's runtime type: a later registration of the same type is ignored (first registration wins).
Exceptions
- ArgumentNullException
interceptoris null.
AddInterceptor(IQueryInterceptor)
Registers a query interceptor that observes the command execution lifecycle of every context this builder creates. Interceptors are invoked in registration order, after the ones already registered.
public DataContextBuilder AddInterceptor(IQueryInterceptor interceptor)
Parameters
interceptorIQueryInterceptorThe interceptor to register; must not be null.
Returns
- DataContextBuilder
This builder, to allow chaining.
Remarks
An instance that also implements IConnectionInterceptor is attached to both event pipelines. Registration is deduplicated by the instance's runtime type: a later registration of the same type is ignored (first registration wins).
Exceptions
- ArgumentNullException
interceptoris null.
AddInterceptor(Type)
Registers an interceptor service key to resolve from the provider captured by this builder when a context is created. The type is validated immediately; the service is resolved once per CreateDataContext() call, honouring the DI lifetime and keeping DI ownership of the resolved instance.
public DataContextBuilder AddInterceptor(Type interceptorType)
Parameters
interceptorTypeTypeThe closed reference type (concrete class, interface or abstract class) to resolve.
Returns
- DataContextBuilder
This builder, to allow chaining.
Remarks
Every registration - an instance or a type - shares one key: the instance's runtime type for an instance, the supplied Type for a type entry. The first registration of a key wins, including mixed instance/type entries, so a later registration of the same key is ignored.
Exceptions
- ArgumentNullException
interceptorTypeis null.- ArgumentException
interceptorTypeis an open generic or value type, or is not assignable to IQueryInterceptor or IConnectionInterceptor.- InvalidOperationException
A context is created on a builder without a captured provider (a standalone builder).
AddInterceptor<T>()
Registers an interceptor service key to resolve from the provider captured by this builder when a context is created; see AddInterceptor(Type).
public DataContextBuilder AddInterceptor<T>() where T : class
Returns
- DataContextBuilder
This builder, to allow chaining.
Type Parameters
TA closed reference type assignable to IQueryInterceptor or IConnectionInterceptor.
Remarks
Every registration - an instance or a type - shares one key: the instance's runtime type for an instance, the supplied Type for a type entry. The first registration of a key wins, including mixed instance/type entries, so a later registration of the same key is ignored.
T is constrained to class at compile time; the runtime
check additionally rejects open-generic and non-assignable types immediately.
Exceptions
- ArgumentException
Tis not a valid interceptor type.- InvalidOperationException
A context is created on a builder without a captured provider.
CreateDataContext()
Creates a data context from the current configuration by invoking Factory. Any interceptor service keys are resolved from the captured provider before the factory is invoked, so a missing registration (or a type entry on a standalone builder) fails before a context is constructed.
public IDataContext CreateDataContext()
Returns
- IDataContext
The configured IDataContext.
Exceptions
- InvalidOperationException
No factory has been configured on this builder, the provider does not have an interceptor registration, or a type entry was registered on a builder without a captured provider.
LogSensitiveData(bool)
Enables or disables logging of command parameter values. Disabled by default; only enable it for local diagnostics, as parameter values may contain sensitive data.
public DataContextBuilder LogSensitiveData(bool logSensitiveData)
Parameters
Returns
- DataContextBuilder
This builder, to allow chaining.
UseCacheSlidingExpiration(TimeSpan)
Enables sliding expiration for the process-wide caches: an entry that is not read within
ttl is evicted lazily. Pass Zero to disable it (the
default). The setting is process-wide because the caches are static, so it applies to every
context created afterwards as well.
public DataContextBuilder UseCacheSlidingExpiration(TimeSpan ttl)
Parameters
Returns
- DataContextBuilder
This builder, to allow chaining.
Exceptions
- ArgumentOutOfRangeException
ttlis negative.
UseCommandTimeout(int)
Sets the default command timeout in seconds for every command of the contexts this builder
creates (the ADO.NET DbCommand.CommandTimeout). A value of zero or less means the
provider default (nothing is changed, the zero-cost path); the same applies before the call. A
single command can override the value with WithCommandTimeout. The resolved timeout is
part of the plan-cache key, so contexts with different defaults do not share a cached command.
The in-memory context has no command and ignores it.
public DataContextBuilder UseCommandTimeout(int seconds)
Parameters
secondsintThe default command timeout in seconds; zero or less uses the provider default.
Returns
- DataContextBuilder
This builder, to allow chaining.
UseEagerLoadMode(EagerLoadMode)
Sets the context-wide default eager-load strategy used by LoadWith when a query declares
no explicit mode. The default is SplitQuery (the historical behavior).
An explicit LoadWith(..., mode) always overrides this setting.
Default is rejected: it is an inheritance sentinel, not a context
setting. Correlated is accepted as configuration, but a
LoadWith that resolves to it fails with NotSupportedException during
preparation (correlated/per-parent top-N execution is not implemented in this release).
public DataContextBuilder UseEagerLoadMode(EagerLoadMode mode)
Parameters
modeEagerLoadModeThe context default; one of SplitQuery, SingleQuery, Correlated or Auto.
Returns
- DataContextBuilder
This builder, to allow chaining.
Exceptions
- ArgumentOutOfRangeException
modeis Default or an undefined numeric value.
UseKeywordCase(KeywordCase)
Sets the letter case in which SQL keywords are emitted. Lower (the
default) emits select ... from ...; Upper emits
SELECT ... FROM .... Identifiers, string literals, function names, type names and raw SQL
are never affected. A single command can override the setting with WithKeywordCase.
public DataContextBuilder UseKeywordCase(KeywordCase keywordCase = KeywordCase.Upper)
Parameters
keywordCaseKeywordCaseThe keyword case to apply.
Returns
- DataContextBuilder
This builder, to allow chaining.
UseLoggerFactory(ILoggerFactory)
Sets the logger factory used for diagnostic logging (SQL text and, when enabled, parameter values).
public DataContextBuilder UseLoggerFactory(ILoggerFactory loggerFactory)
Parameters
loggerFactoryILoggerFactoryThe logger factory to use; must not be null.
Returns
- DataContextBuilder
This builder, to allow chaining.
Exceptions
- ArgumentNullException
loggerFactoryis null.
UseMultilineBatchSql(bool)
Enables rendering of batch SQL with one statement per line: each statement is terminated with
; followed by a newline instead of a space. Intended for readable logs and inspection;
the executed SQL is unaffected (providers using DbBatch never run the joined text, and
SQLite/SQL Server accept the newline).
public DataContextBuilder UseMultilineBatchSql(bool value = true)
Parameters
Returns
- DataContextBuilder
This builder, to allow chaining.
UseNamingConvention(INamingConvention?)
Applies a naming convention to auto-derived table and column names; for example
Instance maps SimpleEntity to
simple_entity and FirstName to first_name. Names declared with
[SqlTable]/[Column] or a fluent mapping are never translated. Pass
null to emit CLR names verbatim (the default). A single command can override
the setting with WithNamingConvention.
public DataContextBuilder UseNamingConvention(INamingConvention? convention)
Parameters
conventionINamingConvention
Returns
UseQueryCache(bool)
Enables (enabled is true, the default) or disables the
implicit plan cache for every context this builder creates. Disabled means each terminal builds
its plan again instead of looking it up; the shared AnyCommand's sticky
QueryCommand.Cache flag is not touched.
public DataContextBuilder UseQueryCache(bool enabled = true)
Parameters
Returns
- DataContextBuilder
This builder, to allow chaining.
UseQuotedIdentifiers(bool)
Enables quoting of physical identifiers (table and column names) in generated SQL, using the
provider's delimiter ("id" on PostgreSQL/SQLite, [id] on SQL Server, `id` on
MySQL/MariaDB/ClickHouse). A single command can override the setting with
WithQuotedIdentifiers.
public DataContextBuilder UseQuotedIdentifiers(bool value = true)
Parameters
valuebool
Returns
UseUppercaseKeywords(bool)
Convenience form of UseKeywordCase(KeywordCase): enables (value is
true) or disables upper-case SQL keywords.
public DataContextBuilder UseUppercaseKeywords(bool value = true)
Parameters
Returns
- DataContextBuilder
This builder, to allow chaining.