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
<PackageReference Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" Version="1.2.53" />
<PackageVersion Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" Version="1.2.53" />
<PackageReference Include="Dosaic.Plugins.Persistence.EfCore.NpgSql" />
paket add Dosaic.Plugins.Persistence.EfCore.NpgSql --version 1.2.53
#r "nuget: Dosaic.Plugins.Persistence.EfCore.NpgSql, 1.2.53"
#:package Dosaic.Plugins.Persistence.EfCore.NpgSql@1.2.53
#addin nuget:?package=Dosaic.Plugins.Persistence.EfCore.NpgSql&version=1.2.53
#tool nuget:?package=Dosaic.Plugins.Persistence.EfCore.NpgSql&version=1.2.53
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:
- Retrieves all pending EF Core migrations and applies them in order.
- After a successful migration run, reloads the Npgsql type map so that any newly created PostgreSQL enum types are immediately usable.
- 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.PostgreSQLwith a fully configuredNpgsqlDataSource - Connection pool tuning — configurable
MaxPoolSize,ConnectionLifetime,KeepAlive, andArrayNullabilityMode=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
SplitQueryto switch betweenSingleQueryandSplitQuerybehaviour globally - Lambda injection —
NeinLinqlambda injection is enabled automatically viaWithLambdaInjection() - 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>(fromDosaic.Plugins.Persistence.EfCore.Abstractions) to expose a readiness health check for the database context - OpenTelemetry instrumentation —
OpenTelemetry.Instrumentation.EntityFrameworkCoreis included automatically
| Product | Versions 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. |
-
net10.0
- Chronos.Abstractions (>= 2.0.24)
- Dosaic.Hosting.Abstractions (>= 1.2.53)
- Dosaic.Plugins.Persistence.EfCore.Abstractions (>= 1.2.53)
- GracefulExpandoObject (>= 1.6.0)
- Linq.Expression.Optimizer (>= 1.0.42)
- LinqKit.Microsoft.EntityFrameworkCore (>= 10.1.1)
- Microsoft.CodeAnalysis.Analyzers (>= 5.9.0)
- Microsoft.CodeAnalysis.CSharp (>= 5.9.0)
- Microsoft.CodeAnalysis.CSharp.Workspaces (>= 5.9.0)
- Microsoft.CodeAnalysis.Workspaces.MSBuild (>= 5.9.0)
- Microsoft.EntityFrameworkCore (>= 10.0.14)
- Microsoft.EntityFrameworkCore.Design (>= 10.0.14)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.14)
- Microsoft.Extensions.Caching.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Caching.Memory (>= 10.0.14)
- Microsoft.Extensions.DependencyInjection (>= 10.0.14)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Diagnostics.HealthChecks.EntityFrameworkCore (>= 10.0.14)
- Microsoft.Extensions.Hosting.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Logging.Abstractions (>= 10.0.14)
- Microsoft.Extensions.Options (>= 10.0.14)
- Microsoft.Extensions.Options.ConfigurationExtensions (>= 10.0.14)
- Nanoid (>= 3.1.0)
- NeinLinq.EntityFrameworkCore (>= 7.4.0)
- Newtonsoft.Json (>= 13.0.4)
- Npgsql (>= 10.0.3)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 10.0.3)
- OpenTelemetry (>= 1.20.1)
- OpenTelemetry.Extensions.Hosting (>= 1.20.1)
- OpenTelemetry.Instrumentation.EntityFrameworkCore (>= 1.20.1-beta.1)
- Vogen (>= 8.0.7)
- YamlDotNet (>= 18.1.0)
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 |