Dosaic.Plugins.Persistence.EfCore.NpgSql 1.2.53

dotnet add package Dosaic.Plugins.Persistence.EfCore.NpgSql --version 1.2.53
                    
NuGet\Install-Package Dosaic.Plugins.Persistence.EfCore.NpgSql -Version 1.2.53
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" Version="1.2.53" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" Version="1.2.53" />
                    
Directory.Packages.props
<PackageReference Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Dosaic.Plugins.Persistence.EfCore.NpgSql --version 1.2.53
                    
#r "nuget: Dosaic.Plugins.Persistence.EfCore.NpgSql, 1.2.53"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Dosaic.Plugins.Persistence.EfCore.NpgSql@1.2.53
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Dosaic.Plugins.Persistence.EfCore.NpgSql&version=1.2.53
                    
Install as a Cake Addin
#tool nuget:?package=Dosaic.Plugins.Persistence.EfCore.NpgSql&version=1.2.53
                    
Install as a Cake Tool

Dosaic.Plugins.Persistence.EfCore.NpgSql

Dosaic.Plugins.Persistence.EfCore.NpgSql is a Dosaic plugin that integrates PostgreSQL into the EF Core persistence layer via the Npgsql provider. It provides connection and pool configuration, automatic PostgreSQL enum mapping via [DbEnumAttribute], lambda injection support, and a hosted background migration service.

Installation

dotnet add package Dosaic.Plugins.Persistence.EfCore.NpgSql

Or add directly to your .csproj:

<PackageReference Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" Version="" />

Configuration

The plugin binds its configuration from the npgsql section via the [Configuration("npgsql")] attribute on EfCoreNpgSqlConfiguration.

appsettings.yml

npgsql:
  host: "localhost"
  port: 5432
  database: "mydb"
  username: "postgres"
  password: "postgres"
  connectionLifetime: 60        # seconds; 0 = indefinite (default: 60)
  keepAlive: 15                 # seconds; 0 = disabled (default: 15)
  maxPoolSize: 100              # (default: 100)
  configureLoggingCacheTimeInSeconds: 300  # (default: 300)
  splitQuery: false             # use SplitQuery behaviour (default: false)
  includeErrorDetail: false     # include PG error details — may expose sensitive data
  enableDetailedErrors: false   # EF Core detailed errors — may expose sensitive data
  enableSensitiveDataLogging: false  # log parameter values — may expose sensitive data
  sslMode: ""                   # Disable|Allow|Prefer|Require|VerifyCA|VerifyFull or verify-full etc.; empty = not set (default)
  rootCertificate: ""           # CA certificate file; empty = not set (default)
  noResetOnClose: false         # true behind pgBouncer in transaction mode (default: false)
  connectionParameters: ""      # raw Npgsql connection string, applied first (default: empty)
  migration:
    maxAttempts: 0              # AddNpgsqlDbMigratorService attempts; 0 = until the host stops (default: 0)
    stopHostOnFailure: false    # true stops the host (exit code 1) after the last attempt (default: false)

connectionParameters is a raw Npgsql connection string (Timeout=5;Application Name=api). It is applied first, and every discrete setting above that is configured overrides it. The defaults of port, connectionLifetime, keepAlive, maxPoolSize and includeErrorDetail only fill in what connectionParameters leaves unset, so connectionParameters: "Port=6432;Maximum Pool Size=20" (pgBouncer) works without repeating those keys. Hangfire applies the same rules to hangfire:connectionParameters. All of this happens before the WithDataSource hook runs, so the hook still has the last word.

sslMode accepts the Npgsql names (VerifyFull) and the libpq names that Helm charts and CloudNativePG use (disable, allow, prefer, require, verify-ca, verify-full). Case is ignored.

host, database and username are required, either as keys or as Host, Database and Username in connectionParameters. Without an npgsql section the host stops at startup with Configuration section 'npgsql' is missing. EfCoreNpgSqlConfiguration is bound from it. Set at least npgsql:host, npgsql:database, npgsql:username (environment: NPGSQL_HOST, NPGSQL_DATABASE, NPGSQL_USERNAME). A section without one of these keys stops it with Configuration section 'npgsql' is incomplete. and the missing keys.

EfCoreNpgSqlPlugin builds the connection string once when the host starts. A missing required key, an unknown sslMode or an unparsable connectionParameters stops the host at startup. The message names the key, and for sslMode it lists the valid values. The plugin does not check that the rootCertificate file exists. The same checks run again when a context is configured, which covers code that calls ConfigureNpgSqlContext outside a Dosaic host.

Configuration class

// Automatically resolved by Dosaic via [Configuration("npgsql")]
[Configuration("npgsql", RequiredKeys = ["host", "database", "username"])]
public class EfCoreNpgSqlConfiguration
{
    public string Host { get; set; }
    public int Port { get; set; } = 5432;
    public string Database { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public int ConnectionLifetime { get; set; } = 60;
    public int KeepAlive { get; set; } = 15;
    public int MaxPoolSize { get; set; } = 100;
    public int ConfigureLoggingCacheTimeInSeconds { get; set; } = 300;
    public bool IncludeErrorDetail { get; set; }
    public bool EnableDetailedErrors { get; set; }
    public bool EnableSensitiveDataLogging { get; set; }
    public bool SplitQuery { get; set; }
    public string SslMode { get; set; }
    public string RootCertificate { get; set; }
    public bool NoResetOnClose { get; set; }
    public string ConnectionParameters { get; set; }
    public StartupRetryOptions Migration { get; set; } = new();
}

Usage

Registering a DbContext in a Dosaic plugin

EfCoreNpgSqlConfiguration is injected automatically by the Dosaic TypeImplementationResolver. Use ConfigureNpgSqlContext<TDbContext> to wire up the Npgsql provider on your DbContextOptionsBuilder.

using Dosaic.Hosting.Abstractions.Plugins;
using Dosaic.Plugins.Persistence.EfCore.Abstractions;
using Dosaic.Plugins.Persistence.EfCore.NpgSql;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

public class MyPlugin(EfCoreNpgSqlConfiguration npgsqlConfig)
    : IPluginServiceConfiguration, IPluginHealthChecksConfiguration
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<MyDbContext>(
            (provider, options) => options.ConfigureNpgSqlContext<MyDbContext>(provider, npgsqlConfig));

        // Optional: run EF migrations in the background on startup
        services.AddNpgsqlDbMigratorService<MyDbContext>();
    }

    public void ConfigureHealthChecks(IHealthChecksBuilder healthChecks)
    {
        healthChecks.AddEfCoreContext<MyDbContext>();
    }
}

Defining a DbContext

using Dosaic.Plugins.Persistence.EfCore.Abstractions.Database;
using Microsoft.EntityFrameworkCore;

public class MyDbContext(DbContextOptions<MyDbContext> options) : EfCoreDbContext(options)
{
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>(e =>
        {
            e.HasKey(x => x.Id);
            e.Property(x => x.Id).IsRequired();
        });

        // register any [DbEnum]-attributed enums for this context
        modelBuilder.MapDbEnums<MyDbContext>();

        base.OnModelCreating(modelBuilder);
    }
}

PostgreSQL enum mapping

Decorate your C# enums with [DbEnum] to have them automatically mapped to PostgreSQL enum types. PostgresEnumExtensions scans all enums bearing this attribute in the assembly of your TDbContext (and in the EF Core Abstractions assembly) and registers them with the Npgsql provider.

using Dosaic.Plugins.Persistence.EfCore.Abstractions.Database;

[DbEnum("order_status", "public")]
public enum OrderStatus
{
    Pending,
    Processing,
    Shipped,
    Delivered,
    Cancelled,
}

The enum values are translated to snake_case names (e.g. Processing → processing) automatically via NpgsqlSnakeCaseNameTranslator.

Advanced: customising the Npgsql options builder

Pass an optional Action<NpgSqlConfiguration> to ConfigureNpgSqlContext to further customise the provider:

services.AddDbContext<MyDbContext>((provider, options) =>
    options.ConfigureNpgSqlContext<MyDbContext>(provider, npgsqlConfig, c =>
    {
        // Provide a pre-built NpgsqlDataSource (e.g. for password rotation)
        c.WithDataSource(dataSourceBuilder =>
        {
            dataSourceBuilder.UsePeriodicPasswordProvider(/* ... */);
        });

        // Fine-tune the Npgsql EF builder
        c.WithNpgSql(npgsql =>
        {
            npgsql.CommandTimeout(60);
        });

        // Override EF Core warning behaviour
        c.WithWarnings(w =>
        {
            w.Log((CoreEventId.RowLimitingOperationWithoutOrderByWarning, LogLevel.Debug));
        });

        // Use a pre-compiled EF Core model (AOT / startup performance)
        c.WithModel(MyDbContextModel.Instance);
    }));

Background migration service

NpgsqlDbMigratorService<TDbContext> is a hosted BackgroundService that:

  1. Retrieves all pending EF Core migrations and applies them in order.
  2. After a successful migration run, reloads the Npgsql type map so that any newly created PostgreSQL enum types are immediately usable.
  3. Retries on failure with a 1-second delay. Every failed attempt is logged with its number.

npgsql:migration:maxAttempts limits the attempts (default 0: until the host stops). After the last failed attempt the error is logged and the host keeps running, unless npgsql:migration:stopHostOnFailure: true stops it with exit code 1. The service reads both keys when the npgsql configuration is registered, which the Dosaic web host does; otherwise it retries until the host stops.

Register it with:

services.AddNpgsqlDbMigratorService<MyDbContext>();

Features

  • Npgsql EF Core provider — connects to PostgreSQL using Npgsql.EntityFrameworkCore.PostgreSQL with a fully configured NpgsqlDataSource
  • Connection pool tuning — configurable MaxPoolSize, ConnectionLifetime, KeepAlive, and ArrayNullabilityMode=PerInstance
  • Automatic PostgreSQL enum mapping — [DbEnumAttribute] marks C# enums; MapDbEnums<TDbContext> registers them on both the data source builder and the model builder with snake_case translation
  • Query splitting — toggle SplitQuery to switch between SingleQuery and SplitQuery behaviour globally
  • Lambda injection — NeinLinq lambda injection is enabled automatically via WithLambdaInjection()
  • Configurable logging — logging cache time, detailed errors, and sensitive data logging are all controlled through configuration
  • Background migrator — NpgsqlDbMigratorService<TDbContext> applies pending migrations on startup and reloads Npgsql types afterward
  • Health check integration — use AddEfCoreContext<TDbContext> (from Dosaic.Plugins.Persistence.EfCore.Abstractions) to expose a readiness health check for the database context
  • OpenTelemetry instrumentation — OpenTelemetry.Instrumentation.EntityFrameworkCore is included automatically
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.2.53 48 11/16/2026
1.2.52 55 11/16/2026
1.2.51 61 11/13/2026
1.2.49 72 11/11/2026
1.2.48 77 11/4/2026
1.2.47 71 11/3/2026
1.2.45 74 10/30/2026
1.2.44 108 10/14/2026
1.2.43 92 10/13/2026
1.2.42 85 9/24/2026
1.2.41 106 9/7/2026
1.2.40 112 8/27/2026
1.2.40-alpha.1 80 8/27/2026
1.2.39 105 8/25/2026
1.2.38 103 7/30/2026
1.2.37 98 7/14/2026
1.2.36 100 7/10/2026
1.2.35 130 6/19/2026
1.2.34 111 6/10/2026
1.2.33 108 6/2/2026
Loading failed