Connect to PostgreSQL with EF Core
Esta página aún no está disponible en tu idioma.
This page describes how .NET consuming apps connect to a PostgreSQL database using Entity Framework Core and the Aspire.Npgsql.EntityFrameworkCore.PostgreSQL client integration. For AppHost setup — adding a PostgreSQL server, databases, pgAdmin, pgWeb, volumes, and more — see PostgreSQL Hosting integration.
EF Core is a .NET-only technology. If your consuming app is written in Go, Python, TypeScript, or another language, see Connect to PostgreSQL for the environment variable reference and per-language examples.
Connection properties
Section titled “Connection properties”When you reference a PostgreSQL resource from your AppHost using WithReference, Aspire injects the connection information into the consuming app as environment variables. Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the ConnectionString property of a resource called postgresdb becomes POSTGRESDB_CONNECTIONSTRING.
PostgreSQL server
Section titled “PostgreSQL server”| Property Name | Environment Variable | Description |
|---|---|---|
Host | [RESOURCE]_HOST | The hostname or IP address of the PostgreSQL server |
Port | [RESOURCE]_PORT | The port number the PostgreSQL server is listening on |
Username | [RESOURCE]_USERNAME | The username for authentication |
Password | [RESOURCE]_PASSWORD | The password for authentication |
PostgreSQL database
Section titled “PostgreSQL database”The PostgreSQL database resource inherits all properties from its parent server resource and adds:
| Property Name | Environment Variable | Description |
|---|---|---|
DatabaseName | [RESOURCE]_DATABASENAME | The name of the database |
JdbcConnectionString | [RESOURCE]_JDBCCONNECTIONSTRING | JDBC-format connection string |
Connect from your app
Section titled “Connect from your app”EF Core is .NET-only. The steps below apply to any .NET consuming app that references a PostgreSQL database resource from the AppHost.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Npgsql.EntityFrameworkCore.PostgreSQL NuGet package in the client-consuming project:
dotnet add package Aspire.Npgsql.EntityFrameworkCore.PostgreSQL#:package Aspire.Npgsql.EntityFrameworkCore.PostgreSQL@*<PackageReference Include="Aspire.Npgsql.EntityFrameworkCore.PostgreSQL" Version="*" />Add the Npgsql DbContext
Section titled “Add the Npgsql DbContext”In Program.cs, call AddNpgsqlDbContext<T> on your IHostApplicationBuilder to register your DbContext subclass in the dependency injection container:
builder.AddNpgsqlDbContext<YourDbContext>(connectionName: "postgresdb");Resolve the DbContext through dependency injection:
public class ExampleService(YourDbContext context){ // Use context to interact with the database...}Add keyed DbContext instances
Section titled “Add keyed DbContext instances”To register more than one DbContext targeting different databases, use the keyed services overload:
builder.AddNpgsqlDbContext<CatalogDbContext>(connectionName: "catalogdb");builder.AddNpgsqlDbContext<OrdersDbContext>(connectionName: "ordersdb");Then resolve each instance by key using [FromKeyedServices]:
public class ExampleService( [FromKeyedServices("catalogdb")] CatalogDbContext catalogContext, [FromKeyedServices("ordersdb")] OrdersDbContext ordersContext){ // Use each context independently...}Enrich an existing DbContext
Section titled “Enrich an existing DbContext”If you already register your DbContext using the standard EF Core approach, you can enhance it with Aspire-style retries, health checks, logging, and telemetry by calling EnrichNpgsqlDbContext:
builder.Services.AddDbContext<YourDbContext>(options => options.UseNpgsql(builder.Configuration.GetConnectionString("postgresdb") ?? throw new InvalidOperationException("Connection string 'postgresdb' not found.")));
builder.EnrichNpgsqlDbContext<YourDbContext>( configureSettings: settings => { settings.DisableRetry = false; settings.CommandTimeout = 30; });Configuration providers
Section titled “Configuration providers”The client integration loads NpgsqlEntityFrameworkCorePostgreSQLSettings from configuration files such as appsettings.json using the Aspire:Npgsql:EntityFrameworkCore:PostgreSQL key:
{ "Aspire": { "Npgsql": { "EntityFrameworkCore": { "PostgreSQL": { "ConnectionString": "Host=myserver;Database=postgresdb", "DisableHealthChecks": false, "DisableTracing": false, "DisableMetrics": false } } } }}To configure multiple DbContext classes with separate settings, use the context type name as a sub-key:
{ "Aspire": { "Npgsql": { "EntityFrameworkCore": { "PostgreSQL": { "ConnectionString": "<DEFAULT CONNECTION STRING>", "AnotherDbContext": { "ConnectionString": "<ANOTHER CONNECTION STRING>", "DisableTracing": false } } } } }}For the complete JSON schema, see Aspire.Npgsql.EntityFrameworkCore.PostgreSQL/ConfigurationSchema.json.
You can also pass inline configuration using an Action<NpgsqlEntityFrameworkCorePostgreSQLSettings> delegate:
builder.AddNpgsqlDbContext<YourDbContext>( "postgresdb", static settings => settings.DisableHealthChecks = true);Health checks
Section titled “Health checks”By default, the integration registers a DbContextHealthCheck that calls EF Core’s CanConnectAsync method. The health check name is the name of the TContext type. It integrates with the /health HTTP endpoint so all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
Microsoft.EntityFrameworkCore.ChangeTrackingMicrosoft.EntityFrameworkCore.Database.CommandMicrosoft.EntityFrameworkCore.Database.ConnectionMicrosoft.EntityFrameworkCore.Database.TransactionMicrosoft.EntityFrameworkCore.MigrationsMicrosoft.EntityFrameworkCore.InfrastructureMicrosoft.EntityFrameworkCore.ModelMicrosoft.EntityFrameworkCore.Model.ValidationMicrosoft.EntityFrameworkCore.QueryMicrosoft.EntityFrameworkCore.Update
Tracing activities:
Npgsql
Metrics:
-
Microsoft.EntityFrameworkCore:
ec_Microsoft_EntityFrameworkCore_active_db_contextsec_Microsoft_EntityFrameworkCore_total_queriesec_Microsoft_EntityFrameworkCore_queries_per_secondec_Microsoft_EntityFrameworkCore_total_save_changesec_Microsoft_EntityFrameworkCore_save_changes_per_secondec_Microsoft_EntityFrameworkCore_compiled_query_cache_hit_rateec_Microsoft_Entity_total_execution_strategy_operation_failuresec_Microsoft_E_execution_strategy_operation_failures_per_secondec_Microsoft_EntityFramew_total_optimistic_concurrency_failuresec_Microsoft_EntityF_optimistic_concurrency_failures_per_second
-
Npgsql:
ec_Npgsql_bytes_written_per_secondec_Npgsql_bytes_read_per_secondec_Npgsql_commands_per_secondec_Npgsql_total_commandsec_Npgsql_current_commandsec_Npgsql_failed_commandsec_Npgsql_prepared_commands_ratioec_Npgsql_connection_poolsec_Npgsql_multiplexing_average_commands_per_batchec_Npgsql_multiplexing_average_write_time_per_batch
Any telemetry feature can be disabled through configuration options above.