# Class NpgsqlDataSourceBuilder

Namespace
  Npgsql

Assembly
  Npgsql.dll

Provides a simple API for configuring and creating an NpgsqlDataSource, from which database connections can be obtained.

    public sealed class NpgsqlDataSourceBuilder : INpgsqlTypeMapper

Inheritance
  object
  NpgsqlDataSourceBuilder

Implements
  INpgsqlTypeMapper

Inherited Members
  object.Equals(object)
  object.Equals(object, object)
  object.GetHashCode()
  object.GetType()
  object.ReferenceEquals(object, object)
  object.ToString()

## Constructors

### NpgsqlDataSourceBuilder(string?)

Constructs a new NpgsqlDataSourceBuilder, optionally starting out from the given `connectionString`.

    public NpgsqlDataSourceBuilder(string? connectionString = null)

#### Parameters

`connectionString` string

## Properties

### ConnectionString

Returns the connection string, as currently configured on the builder.

    public string ConnectionString { get; }

#### Property Value

string

### ConnectionStringBuilder

A connection string builder that can be used to configured the connection string on the builder.

    public NpgsqlConnectionStringBuilder ConnectionStringBuilder { get; }

#### Property Value

NpgsqlConnectionStringBuilder

### DefaultNameTranslator

The default name translator to convert CLR type names and member names. Defaults to NpgsqlSnakeCaseNameTranslator.

    public INpgsqlNameTranslator DefaultNameTranslator { get; set; }

#### Property Value

INpgsqlNameTranslator

### Name

A diagnostics name used by Npgsql when generating tracing, logging and metrics.

    public string? Name { get; set; }

#### Property Value

string

## Methods

### AddTypeInfoResolverFactory(PgTypeInfoResolverFactory)

Adds a type info resolver factory which can add or modify support for PostgreSQL types. Typically used by plugins.

    public void AddTypeInfoResolverFactory(PgTypeInfoResolverFactory factory)

#### Parameters

`factory` PgTypeInfoResolverFactory

  The type resolver factory to be added.

### Build()

Builds and returns an NpgsqlDataSource which is ready for use.

    public NpgsqlDataSource Build()

#### Returns

NpgsqlDataSource

### BuildMultiHost()

Builds and returns a NpgsqlMultiHostDataSource which is ready for use for load-balancing and failover scenarios.

    public NpgsqlMultiHostDataSource BuildMultiHost()

#### Returns

NpgsqlMultiHostDataSource

### ConfigureJsonOptions(JsonSerializerOptions)

Configures the JSON serializer options used when reading and writing all System.Text.Json data.

    public NpgsqlDataSourceBuilder ConfigureJsonOptions(JsonSerializerOptions serializerOptions)

#### Parameters

`serializerOptions` JsonSerializerOptions

  Options to customize JSON serialization and deserialization.

#### Returns

NpgsqlDataSourceBuilder

### EnableDynamicJson(Type[]?, Type[]?)

Sets up dynamic System.Text.Json mappings. This allows mapping arbitrary .NET types to PostgreSQL `json` and `jsonb` types, as well as JsonNode and its derived types.

    [RequiresUnreferencedCode("Json serializer may perform reflection on trimmed types.")]
    [RequiresDynamicCode("Serializing arbitrary types to json can require creating new generic types or methods, which requires creating code at runtime. This may not work when AOT compiling.")]
    public NpgsqlDataSourceBuilder EnableDynamicJson(Type[]? jsonbClrTypes = null, Type[]? jsonClrTypes = null)

#### Parameters

`jsonbClrTypes` Type[]

  A list of CLR types to map to PostgreSQL `jsonb` (no need to specify Jsonb).

`jsonClrTypes` Type[]

  A list of CLR types to map to PostgreSQL `json` (no need to specify Json).

#### Returns

NpgsqlDataSourceBuilder

#### Remarks

Due to the dynamic nature of these mappings, they are not compatible with NativeAOT or trimming.

### EnableParameterLogging(bool)

Enables parameters to be included in logging. This includes potentially sensitive information from data sent to PostgreSQL. You should only enable this flag in development, or if you have the appropriate security measures in place based on the sensitivity of this data.

    public NpgsqlDataSourceBuilder EnableParameterLogging(bool parameterLoggingEnabled = true)

#### Parameters

`parameterLoggingEnabled` bool

  If true, then sensitive data is logged.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### EnableRecordsAsTuples()

Sets up mappings for the PostgreSQL `record` type as a .NET ValueTuple or Tuple.

    [RequiresUnreferencedCode("The mapping of PostgreSQL records as .NET tuples requires reflection usage which is incompatible with trimming.")]
    [RequiresDynamicCode("The mapping of PostgreSQL records as .NET tuples requires dynamic code usage which is incompatible with NativeAOT.")]
    public NpgsqlDataSourceBuilder EnableRecordsAsTuples()

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### EnableUnmappedTypes()

Sets up mappings allowing the use of unmapped enum, range and multirange types.

    [RequiresUnreferencedCode("The use of unmapped enums, ranges or multiranges requires reflection usage which is incompatible with trimming.")]
    [RequiresDynamicCode("The use of unmapped enums, ranges or multiranges requires dynamic code usage which is incompatible with NativeAOT.")]
    public NpgsqlDataSourceBuilder EnableUnmappedTypes()

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### MapComposite(Type, string?, INpgsqlNameTranslator?)

Maps a CLR type to a composite type.

    [RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
    public INpgsqlTypeMapper MapComposite(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

#### Parameters

`clrType` Type

  The .NET type to be mapped.

`pgName` string

  A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

INpgsqlTypeMapper

#### Remarks

Maps CLR fields and properties by string to PostgreSQL names. The translation strategy can be controlled by the `nameTranslator` parameter, which defaults to DefaultNameTranslator. If there is a discrepancy between the .NET type and database type while a composite is read or written, an exception will be raised.

### MapComposite<T>(string?, INpgsqlNameTranslator?)

Maps a CLR type to a PostgreSQL composite type.

    [RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
    public INpgsqlTypeMapper MapComposite<T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

#### Parameters

`pgName` string

  A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

INpgsqlTypeMapper

#### Type Parameters

`T`

  The .NET type to be mapped

#### Remarks

CLR fields and properties by string to PostgreSQL names. The translation strategy can be controlled by the `nameTranslator` parameter, which defaults to NpgsqlSnakeCaseNameTranslator. You can also use the PgNameAttribute on your members to manually specify a PostgreSQL name. If there is a discrepancy between the .NET type and database type while a composite is read or written, an exception will be raised.

### MapEnum(Type, string?, INpgsqlNameTranslator?)

Maps a CLR enum to a PostgreSQL enum type.

    [RequiresDynamicCode("Calling MapEnum with a Type can require creating new generic types or methods. This may not work when AOT compiling.")]
    public INpgsqlTypeMapper MapEnum(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

#### Parameters

`clrType` Type

  The .NET enum type to be mapped

`pgName` string

  A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

INpgsqlTypeMapper

#### Remarks

CLR enum labels are mapped by name to PostgreSQL enum labels. The translation strategy can be controlled by the `nameTranslator` parameter, which defaults to NpgsqlSnakeCaseNameTranslator. You can also use the PgNameAttribute on your enum fields to manually specify a PostgreSQL enum label. If there is a discrepancy between the .NET and database labels while an enum is read or written, an exception will be raised.

### MapEnum<TEnum>(string?, INpgsqlNameTranslator?)

Maps a CLR enum to a PostgreSQL enum type.

    public INpgsqlTypeMapper MapEnum<TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum

#### Parameters

`pgName` string

  A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

INpgsqlTypeMapper

#### Type Parameters

`TEnum`

  The .NET enum type to be mapped

#### Remarks

CLR enum labels are mapped by name to PostgreSQL enum labels. The translation strategy can be controlled by the `nameTranslator` parameter, which defaults to NpgsqlSnakeCaseNameTranslator. You can also use the PgNameAttribute on your enum fields to manually specify a PostgreSQL enum label. If there is a discrepancy between the .NET and database labels while an enum is read or written, an exception will be raised.

### UnmapComposite(Type, string?, INpgsqlNameTranslator?)

Removes an existing composite mapping.

    [RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
    public bool UnmapComposite(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

#### Parameters

`clrType` Type

  The .NET type to be unmapped.

`pgName` string

  A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

bool

### UnmapComposite<T>(string?, INpgsqlNameTranslator?)

Removes an existing composite mapping.

    [RequiresDynamicCode("Mapping composite types involves serializing arbitrary types which can require creating new generic types or methods. This is currently unsupported with NativeAOT, vote on issue #5303 if this is important to you.")]
    public bool UnmapComposite<T>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

#### Parameters

`pgName` string

  A PostgreSQL type name for the corresponding composite type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to NpgsqlSnakeCaseNameTranslator

#### Returns

bool

#### Type Parameters

`T`

### UnmapEnum(Type, string?, INpgsqlNameTranslator?)

Removes an existing enum mapping.

    public bool UnmapEnum(Type clrType, string? pgName = null, INpgsqlNameTranslator? nameTranslator = null)

#### Parameters

`clrType` Type

  The .NET enum type to be mapped

`pgName` string

  A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

bool

### UnmapEnum<TEnum>(string?, INpgsqlNameTranslator?)

Removes an existing enum mapping.

    public bool UnmapEnum<TEnum>(string? pgName = null, INpgsqlNameTranslator? nameTranslator = null) where TEnum : struct, Enum

#### Parameters

`pgName` string

  A PostgreSQL type name for the corresponding enum type in the database. If null, the name translator given in `nameTranslator` will be used.

`nameTranslator` INpgsqlNameTranslator

  A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). Defaults to DefaultNameTranslator.

#### Returns

bool

#### Type Parameters

`TEnum`

### UseClientCertificate(X509Certificate?)

Specifies an SSL/TLS certificate which Npgsql will send to PostgreSQL for certificate-based authentication.

    public NpgsqlDataSourceBuilder UseClientCertificate(X509Certificate? clientCertificate)

#### Parameters

`clientCertificate` X509Certificate

  The client certificate to be sent to PostgreSQL when opening a connection.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### UseClientCertificates(X509CertificateCollection?)

Specifies a collection of SSL/TLS certificates which Npgsql will send to PostgreSQL for certificate-based authentication.

    public NpgsqlDataSourceBuilder UseClientCertificates(X509CertificateCollection? clientCertificates)

#### Parameters

`clientCertificates` X509CertificateCollection

  The client certificate collection to be sent to PostgreSQL when opening a connection.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### UseClientCertificatesCallback(Action<X509CertificateCollection>?)

Specifies a callback to modify the collection of SSL/TLS client certificates which Npgsql will send to PostgreSQL for certificate-based authentication. This is an advanced API, consider using UseClientCertificate(X509Certificate?) or UseClientCertificates(X509CertificateCollection?) instead.

    public NpgsqlDataSourceBuilder UseClientCertificatesCallback(Action<X509CertificateCollection>? clientCertificatesCallback)

#### Parameters

`clientCertificatesCallback` Action<X509CertificateCollection>

  The callback to modify the client certificate collection.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

#### Remarks

The callback is invoked every time a physical connection is opened, and is therefore suitable for rotating short-lived client certificates. Simply make sure the certificate collection argument has the up-to-date certificate(s).

The callback's collection argument already includes any client certificates specified via the connection string or environment variables.

### UseLoggerFactory(ILoggerFactory?)

Sets the ILoggerFactory that will be used for logging.

    public NpgsqlDataSourceBuilder UseLoggerFactory(ILoggerFactory? loggerFactory)

#### Parameters

`loggerFactory` ILoggerFactory

  The logger factory to be used.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### UsePasswordProvider(Func<NpgsqlConnectionStringBuilder, string>?, Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>?)

Configures a password provider, which is called by the data source when opening connections.

    public NpgsqlDataSourceBuilder UsePasswordProvider(Func<NpgsqlConnectionStringBuilder, string>? passwordProvider, Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>? passwordProviderAsync)

#### Parameters

`passwordProvider` Func<NpgsqlConnectionStringBuilder, string>

  A callback that may be invoked during Open() which returns the password to be sent to PostgreSQL.

`passwordProviderAsync` Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>

  A callback that may be invoked during OpenAsync(CancellationToken) which returns the password to be sent to PostgreSQL.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

#### Remarks

The provided callback is invoked when opening connections. Therefore its important the callback internally depends on cached data or returns quickly otherwise. Any unnecessary delay will affect connection opening time.

### UsePeriodicPasswordProvider(Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>?, TimeSpan, TimeSpan)

Configures a periodic password provider, which is automatically called by the data source at some regular interval. This is the recommended way to fetch a rotating access token.

    public NpgsqlDataSourceBuilder UsePeriodicPasswordProvider(Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>? passwordProvider, TimeSpan successRefreshInterval, TimeSpan failureRefreshInterval)

#### Parameters

`passwordProvider` Func<NpgsqlConnectionStringBuilder, CancellationToken, ValueTask<string>>

  A callback which returns the password to be sent to PostgreSQL.

`successRefreshInterval` TimeSpan

  How long to cache the password before re-invoking the callback.

`failureRefreshInterval` TimeSpan

  If a password refresh attempt fails, it will be re-attempted with this interval. This should typically be much lower than `successRefreshInterval`.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

#### Remarks

The provided callback is invoked in a timer, and not when opening connections. It therefore doesn't affect opening time.

The provided cancellation token is only triggered when the entire data source is disposed. If you'd like to apply a timeout to the token fetching, do so within the provided callback.

### UsePhysicalConnectionInitializer(Action<NpgsqlConnection>?, Func<NpgsqlConnection, Task>?)

Register a connection initializer, which allows executing arbitrary commands when a physical database connection is first opened.

    public NpgsqlDataSourceBuilder UsePhysicalConnectionInitializer(Action<NpgsqlConnection>? connectionInitializer, Func<NpgsqlConnection, Task>? connectionInitializerAsync)

#### Parameters

`connectionInitializer` Action<NpgsqlConnection>

  A synchronous connection initialization lambda, which will be called from Open() when a new physical connection is opened.

`connectionInitializerAsync` Func<NpgsqlConnection, Task>

  An asynchronous connection initialization lambda, which will be called from OpenAsync(CancellationToken) when a new physical connection is opened.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

#### Remarks

If an initializer is registered, both sync and async versions must be provided. If you do not use sync APIs in your code, simply throw NotSupportedException, which would also catch accidental cases of sync opening.

### UseRootCertificate(X509Certificate2?)

Sets the X509Certificate2 that will be used validate SSL certificate, received from the server.

    public NpgsqlDataSourceBuilder UseRootCertificate(X509Certificate2? rootCertificate)

#### Parameters

`rootCertificate` X509Certificate2

  The CA certificate.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

### UseRootCertificateCallback(Func<X509Certificate2>?)

Specifies a callback that will be used to validate SSL certificate, received from the server.

    public NpgsqlDataSourceBuilder UseRootCertificateCallback(Func<X509Certificate2>? rootCertificateCallback)

#### Parameters

`rootCertificateCallback` Func<X509Certificate2>

  The callback to get CA certificate.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

#### Remarks

This overload, which accepts a callback, is suitable for scenarios where the certificate rotates and might change during the lifetime of the application. When that's not the case, use the overload which directly accepts the certificate.

### UseUserCertificateValidationCallback(RemoteCertificateValidationCallback)

When using SSL/TLS, this is a callback that allows customizing how the PostgreSQL-provided certificate is verified. This is an advanced API, consider using VerifyFull or VerifyCA instead.

    public NpgsqlDataSourceBuilder UseUserCertificateValidationCallback(RemoteCertificateValidationCallback userCertificateValidationCallback)

#### Parameters

`userCertificateValidationCallback` RemoteCertificateValidationCallback

  The callback containing custom callback verification logic.

#### Returns

NpgsqlDataSourceBuilder

  The same builder instance so that multiple calls can be chained.

#### Remarks

Cannot be used in conjunction with Disable, VerifyCA or VerifyFull.

See https://msdn.microsoft.com/en-us/library/system.net.security.remotecertificatevalidationcallback(v=vs.110).aspx.