PostgreSQL
suggest changeFrom C# you talk to PostgreSQL through Npgsql, an open-source ADO.NET provider. It uses the same Connection / Command / DataReader model as the other providers (see MySQL and ADO.NET Connections). It also supports PostgreSQL-specific features: arrays, jsonb, COPY, LISTEN/NOTIFY and batching. Dapper and the EF Core provider (Npgsql.EntityFrameworkCore.PostgreSQL) both run on top of it.
The examples are .NET 10 file-based programs (dotnet run app.cs) using Npgsql 10.0 against PostgreSQL 18. All output comes from real runs.
Installing
In a project:
dotnet add package Npgsql
In a file-based program, put the package reference at the top of the file:
#:package Npgsql@10.0.3
To get a server for local testing:
docker run -d --name pg -p 5432:5432 -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=shop postgres:18
NpgsqlDataSource
Npgsql 7 introduced NpgsqlDataSource, and it is the recommended entry point. A data source holds the connection string, the connection pool and the type mapping configuration. Create one when the app starts and share it everywhere. It is thread-safe.
#:package Npgsql@10.0.3
using Npgsql;
const string ConnStr = "Host=localhost;Port=5432;Username=postgres;Password=secret;Database=shop";
await using var dataSource = NpgsqlDataSource.Create(ConnStr);
await using (var cmd = dataSource.CreateCommand("""
DROP TABLE IF EXISTS products;
CREATE TABLE products (
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL UNIQUE,
price numeric(10,2) NOT NULL,
tags text[] NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now()
)
"""))
{
await cmd.ExecuteNonQueryAsync();
}
await using (var cmd = dataSource.CreateCommand("SELECT version()"))
{
var version = (string)(await cmd.ExecuteScalarAsync())!;
Console.WriteLine(version);
}
await using var conn = await dataSource.OpenConnectionAsync();
Console.WriteLine($"PostgreSQL {conn.PostgreSqlVersion}, state: {conn.State}");
PostgreSQL 18.4 on x86_64-windows, compiled by msvc-19.44.35226, 64-bit
PostgreSQL 18.4, state: Open
dataSource.CreateCommand(sql) returns a command that takes a pooled connection when it runs and gives it back when it finishes. When you need several statements on the same connection (a transaction, COPY, LISTEN), call OpenConnectionAsync instead. Disposing an NpgsqlConnection returns it to the pool; it doesn't close the socket. See Database connection pooling for how pooling works.
Use NpgsqlConnectionStringBuilder to build connection strings from configuration values without typos. Useful keywords include Maximum Pool Size, Timeout (connect timeout in seconds), Command Timeout (default 30 seconds), SSL Mode=Require and Include Error Detail.
Parameters
Never concatenate values into SQL. Npgsql supports two styles of placeholders.
Positional $1, $2, ... is PostgreSQL's native syntax. Add parameters without names, in order. This is the fastest option, because Npgsql sends the SQL to the server unchanged.
Named @name placeholders are rewritten by Npgsql into $n before sending. This is convenient and it is what Dapper uses.
#:package Npgsql@10.0.3
using Npgsql;
const string ConnStr = "Host=localhost;Port=5432;Username=postgres;Password=secret;Database=shop";
await using var dataSource = NpgsqlDataSource.Create(ConnStr);
// Named parameters
await using (var cmd = dataSource.CreateCommand(
"INSERT INTO products (name, price, tags) VALUES (@name, @price, @tags) RETURNING id"))
{
cmd.Parameters.AddWithValue("name", "Keyboard");
cmd.Parameters.AddWithValue("price", 49.99m);
cmd.Parameters.AddWithValue("tags", new[] { "usb", "office" });
var id = (int)(await cmd.ExecuteScalarAsync())!;
Console.WriteLine($"inserted id {id}");
}
// Positional parameters: $1, $2 ... with unnamed NpgsqlParameter
await using (var cmd = dataSource.CreateCommand(
"INSERT INTO products (name, price, tags) VALUES ($1, $2, $3) RETURNING id, created_at"))
{
cmd.Parameters.Add(new() { Value = "Mouse" });
cmd.Parameters.Add(new() { Value = 19.50m });
cmd.Parameters.Add(new() { Value = new[] { "usb", "wireless" } });
await using var reader = await cmd.ExecuteReaderAsync();
await reader.ReadAsync();
Console.WriteLine($"inserted id {reader.GetInt32(0)}, created_at kind: {reader.GetDateTime(1).Kind}");
}
// Strongly typed parameters avoid boxing
await using (var cmd = dataSource.CreateCommand(
"INSERT INTO products (name, price) VALUES ($1, $2)"))
{
cmd.Parameters.Add(new NpgsqlParameter<string> { TypedValue = "Monitor" });
cmd.Parameters.Add(new NpgsqlParameter<decimal> { TypedValue = 199m });
Console.WriteLine($"rows affected: {await cmd.ExecuteNonQueryAsync()}");
}
inserted id 1
inserted id 2, created_at kind: Utc
rows affected: 1
Each command must use only one style. You can't mix @name and $1 in the same command.
There is no LastInsertedId in PostgreSQL. Use RETURNING, which gives back any columns of the inserted, updated or deleted rows, including defaults filled in by the server.
Reading rows
await using (var cmd = dataSource.CreateCommand(
"SELECT id, name, price, tags FROM products WHERE price < $1 ORDER BY id"))
{
cmd.Parameters.Add(new() { Value = 100m });
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
int id = reader.GetInt32(0);
string name = reader.GetString(1);
decimal price = reader.GetDecimal(2);
string[] tags = reader.GetFieldValue<string[]>(3);
Console.WriteLine($"{id}: {name,-10} {price,7} [{string.Join(", ", tags)}]");
}
}
// Array parameter with = ANY instead of building an IN (...) list
await using (var cmd = dataSource.CreateCommand(
"SELECT name FROM products WHERE id = ANY($1) ORDER BY name"))
{
cmd.Parameters.Add(new() { Value = new[] { 1, 3 } });
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
Console.WriteLine(reader.GetString(0));
}
// UPDATE ... RETURNING shows the new values
await using (var cmd = dataSource.CreateCommand(
"UPDATE products SET price = price * 0.9 WHERE 'usb' = ANY(tags) RETURNING name, price"))
{
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
Console.WriteLine($"{reader.GetString(0)} now costs {reader.GetDecimal(1)}");
}
1: Keyboard 49.99 [usb, office]
2: Mouse 19.50 [usb, wireless]
Keyboard
Monitor
Keyboard now costs 44.99
Mouse now costs 17.55
PostgreSQL arrays map directly to C# arrays and List<T>, both as parameters and as results. id = ANY($1) with an int[] parameter replaces dynamically built IN (...) lists. The SQL text stays the same no matter how many ids you pass, so the server can reuse the prepared statement.
Type mapping notes:
integerisint,bigintislong, andcount(*)returnsbigint, so read it withGetInt64.numericisdecimal,text/varcharisstring,booleanisbool,uuidisGuid,byteaisbyte[].datereads asDateOnly(viaGetFieldValue<DateOnly>) andtimeasTimeOnly.- To store
NULL, passDBNull.Value. To read a nullable column, checkreader.IsDBNull(i)first.
Dates and times
Npgsql is strict about time zones. A timestamptz column holds an instant, and Npgsql reads it as a DateTime with Kind=Utc. When you write a DateTime to a timestamptz, it must have Kind=Utc. A timestamp (without time zone) column takes Kind=Local or Kind=Unspecified values.
await using var cmd = dataSource.CreateCommand(
"INSERT INTO events (kind, payload, happened, day) VALUES ('x', '{}', $1, current_date)");
cmd.Parameters.Add(new()
{
Value = new DateTime(2026, 10, 17, 12, 30, 0, DateTimeKind.Local),
NpgsqlDbType = NpgsqlDbType.TimestampTz,
});
await cmd.ExecuteNonQueryAsync();
ArgumentException: Cannot write DateTime with Kind=Local to PostgreSQL type 'timestamp with time zone', only UTC is supported. Note that it's not possible to mix DateTimes with different Kinds in an array, range, or multirange. (Parameter 'value')
Use DateTime.UtcNow or DateTimeOffset (with offset zero) for timestamptz. In most apps, use timestamptz for every column that records when something happened.
JSON and jsonb
jsonb stores parsed JSON that you can index and query. You can always send JSON as a string (set NpgsqlDbType.Jsonb). If you call EnableDynamicJson() on the data source builder, Npgsql also serializes and deserializes your own types with System.Text.Json:
#:package Npgsql@10.0.3
#:property PublishAot=false
using Npgsql;
using NpgsqlTypes;
const string ConnStr = "Host=localhost;Port=5432;Username=postgres;Password=secret;Database=shop";
var builder = new NpgsqlDataSourceBuilder(ConnStr);
builder.EnableDynamicJson();
await using var dataSource = builder.Build();
await dataSource.CreateCommand("""
DROP TABLE IF EXISTS events;
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
kind text NOT NULL,
note text,
payload jsonb NOT NULL,
happened timestamptz NOT NULL,
day date NOT NULL
)
""").ExecuteNonQueryAsync();
// jsonb from a record, NULL from DBNull, timestamptz from UTC DateTime, date from DateOnly
await using (var cmd = dataSource.CreateCommand(
"INSERT INTO events (kind, note, payload, happened, day) VALUES ($1, $2, $3, $4, $5)"))
{
cmd.Parameters.Add(new() { Value = "order" });
cmd.Parameters.Add(new() { Value = DBNull.Value });
cmd.Parameters.Add(new() { Value = new Order("A-17", 3, ["express"]), NpgsqlDbType = NpgsqlDbType.Jsonb });
cmd.Parameters.Add(new() { Value = new DateTime(2026, 10, 17, 12, 30, 0, DateTimeKind.Utc) });
cmd.Parameters.Add(new() { Value = new DateOnly(2026, 10, 17) });
await cmd.ExecuteNonQueryAsync();
}
await using (var cmd = dataSource.CreateCommand("""
SELECT note, payload, payload->>'Sku', happened, day
FROM events WHERE payload @> $1
"""))
{
cmd.Parameters.Add(new() { Value = """{"Quantity": 3}""", NpgsqlDbType = NpgsqlDbType.Jsonb });
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
string? note = reader.IsDBNull(0) ? null : reader.GetString(0);
Order order = reader.GetFieldValue<Order>(1);
string raw = reader.GetString(1);
string sku = reader.GetString(2);
DateTime happened = reader.GetDateTime(3);
DateOnly day = reader.GetFieldValue<DateOnly>(4);
Console.WriteLine($"note={note ?? "(null)"} sku={sku} day={day:yyyy-MM-dd}");
Console.WriteLine($"happened={happened:O}");
Console.WriteLine($"order: {order.Sku} x{order.Quantity} [{string.Join(", ", order.Flags)}]");
Console.WriteLine($"raw={raw}");
}
}
record Order(string Sku, int Quantity, string[] Flags);
note=(null) sku=A-17 day=2026-10-17
happened=2026-10-17T12:30:00.0000000Z
order: A-17 x3 [express]
raw={"Sku": "A-17", "Flags": ["express"], "Quantity": 3}
->> extracts a field as text and @> tests containment, which a GIN index on the column can speed up. The raw output shows that jsonb doesn't keep the original key order or whitespace.
File-based programs are AOT-compatible by default, which turns off reflection-based JSON serialization. The #:property PublishAot=false line turns it back on. A normal .csproj project doesn't need it.
Transactions
await dataSource.CreateCommand("""
DROP TABLE IF EXISTS accounts;
CREATE TABLE accounts (
id integer PRIMARY KEY,
owner text NOT NULL,
balance numeric NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 'alice', 100), (2, 'bob', 50);
""").ExecuteNonQueryAsync();
async Task TransferAsync(int from, int to, decimal amount)
{
await using var conn = await dataSource.OpenConnectionAsync();
await using var tx = await conn.BeginTransactionAsync();
await using var debit = new NpgsqlCommand(
"UPDATE accounts SET balance = balance - $1 WHERE id = $2", conn, tx);
debit.Parameters.Add(new() { Value = amount });
debit.Parameters.Add(new() { Value = from });
await debit.ExecuteNonQueryAsync();
await using var credit = new NpgsqlCommand(
"UPDATE accounts SET balance = balance + $1 WHERE id = $2", conn, tx);
credit.Parameters.Add(new() { Value = amount });
credit.Parameters.Add(new() { Value = to });
await credit.ExecuteNonQueryAsync();
await tx.CommitAsync();
}
async Task PrintBalancesAsync()
{
await using var cmd = dataSource.CreateCommand("SELECT owner, balance FROM accounts ORDER BY id");
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
Console.Write($"{reader.GetString(0)}={reader.GetDecimal(1)} ");
Console.WriteLine();
}
await TransferAsync(1, 2, 30m);
await PrintBalancesAsync();
try
{
await TransferAsync(1, 2, 500m);
}
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.CheckViolation)
{
Console.WriteLine($"{ex.SqlState}: {ex.MessageText} (constraint {ex.ConstraintName})");
}
await PrintBalancesAsync();
alice=70 bob=80
23514: new row for relation "accounts" violates check constraint "accounts_balance_check" (constraint accounts_balance_check)
alice=70 bob=80
You don't need an explicit try/RollbackAsync. If the transaction is disposed without CommitAsync, Npgsql rolls it back. In PostgreSQL, a statement that fails inside a transaction aborts the whole transaction, and every later command fails until you roll back. To recover from one failed statement and continue, use a savepoint (tx.SaveAsync("sp") and tx.RollbackAsync("sp")).
BeginTransactionAsync(IsolationLevel.Serializable) gives you serializable isolation. With it, be ready to retry when you get PostgresErrorCodes.SerializationFailure (40001).
Errors and upserts
Errors raised by the server come as PostgresException. Its SqlState holds the standard five-character code, and PostgresErrorCodes has a constant for each one. Network and protocol problems come as the base class NpgsqlException.
await dataSource.CreateCommand("INSERT INTO products (name, price) VALUES ('Cable', 5)").ExecuteNonQueryAsync();
try
{
await dataSource.CreateCommand("INSERT INTO products (name, price) VALUES ('Cable', 6)").ExecuteNonQueryAsync();
}
catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.UniqueViolation)
{
Console.WriteLine($"duplicate: {ex.ConstraintName} / {ex.Detail}");
}
duplicate: products_name_key / Detail redacted as it may contain sensitive data. Specify 'Include Error Detail' in the connection string to include this information.
The detail usually contains row values, so Npgsql hides it by default. Add Include Error Detail=true to the connection string in development to see it.
Often you don't need to catch the duplicate at all. INSERT ... ON CONFLICT does an atomic upsert:
async Task<(int Id, bool Inserted)> UpsertAsync(string name, decimal price)
{
await using var cmd = dataSource.CreateCommand("""
INSERT INTO products (name, price) VALUES ($1, $2)
ON CONFLICT (name) DO UPDATE SET price = EXCLUDED.price
RETURNING id, (xmax = 0) AS inserted
""");
cmd.Parameters.Add(new() { Value = name });
cmd.Parameters.Add(new() { Value = price });
await using var reader = await cmd.ExecuteReaderAsync();
await reader.ReadAsync();
return (reader.GetInt32(0), reader.GetBoolean(1));
}
Console.WriteLine(await UpsertAsync("Cable", 6.50m));
Console.WriteLine(await UpsertAsync("Hub", 25m));
(1, False)
(4, True)
EXCLUDED refers to the row you tried to insert. xmax = 0 is a common trick for telling whether the row was inserted or updated. Hub got id 4, not 2, because the failed insert and the upsert of Cable each used up a sequence value. Identity values can have gaps, so never rely on them being consecutive.
Batching
NpgsqlBatch sends several statements in one network round trip. Each statement can have its own parameters and its own result set:
await using (var batch = dataSource.CreateBatch())
{
batch.BatchCommands.Add(new NpgsqlBatchCommand("UPDATE products SET price = price + 1 WHERE name = $1")
{ Parameters = { new() { Value = "Hub" } } });
batch.BatchCommands.Add(new NpgsqlBatchCommand("SELECT count(*) FROM products"));
batch.BatchCommands.Add(new NpgsqlBatchCommand("SELECT name, price FROM products ORDER BY id"));
await using var reader = await batch.ExecuteReaderAsync();
await reader.ReadAsync();
Console.WriteLine($"count: {reader.GetInt64(0)}");
await reader.NextResultAsync();
while (await reader.ReadAsync())
Console.WriteLine($" {reader.GetString(0)} {reader.GetDecimal(1)}");
Console.WriteLine($"UPDATE affected {batch.BatchCommands[0].RecordsAffected} row(s)");
}
count: 2
Cable 6.50
Hub 26.00
UPDATE affected 1 row(s)
A batch runs in an implicit transaction: if one statement fails, none of them take effect. The UPDATE produces no result set, so the reader starts at the first SELECT.
Bulk import with COPY
Inserting many rows with one INSERT per row is slow. COPY ... FROM STDIN (FORMAT BINARY) streams rows to the server and is usually the fastest way to load data:
await using (var conn = await dataSource.OpenConnectionAsync())
{
var sw = Stopwatch.StartNew();
await using (var writer = await conn.BeginBinaryImportAsync(
"COPY products (name, price, tags) FROM STDIN (FORMAT BINARY)"))
{
for (int i = 0; i < 100_000; i++)
{
await writer.StartRowAsync();
await writer.WriteAsync($"item-{i}", NpgsqlDbType.Text);
await writer.WriteAsync(1m + i % 100, NpgsqlDbType.Numeric);
await writer.WriteAsync(new[] { "bulk" }, NpgsqlDbType.Array | NpgsqlDbType.Text);
}
ulong rows = await writer.CompleteAsync();
Console.WriteLine($"copied {rows:N0} rows in {sw.ElapsedMilliseconds} ms");
}
await using var reader = await conn.BeginBinaryExportAsync(
"COPY (SELECT name, price FROM products ORDER BY id LIMIT 3) TO STDOUT (FORMAT BINARY)");
while (await reader.StartRowAsync() != -1)
{
string name = await reader.ReadAsync<string>();
decimal price = await reader.ReadAsync<decimal>();
Console.WriteLine($"exported {name} {price}");
}
}
copied 100,000 rows in 1110 ms
exported Cable 6.50
exported Hub 26.00
exported item-0 1.00
Write the columns in the same order as the column list, and pass the NpgsqlDbType because the binary format has no implicit conversions. Writing a C# int into a bigint column fails. If you dispose the writer without calling CompleteAsync, the import is cancelled and no rows are inserted.
LISTEN / NOTIFY
PostgreSQL has a lightweight pub/sub built in. A listening connection receives notifications through the Notification event, which fires while you wait in WaitAsync:
// A dedicated connection that stays open for listening
await using var listener = await dataSource.OpenConnectionAsync();
listener.Notification += (_, e) =>
Console.WriteLine($"[{e.Channel}] {e.Payload} (from backend pid {e.PID})");
await using (var cmd = new NpgsqlCommand("LISTEN orders", listener))
await cmd.ExecuteNonQueryAsync();
// Somebody else sends notifications
_ = Task.Run(async () =>
{
for (int i = 1; i <= 3; i++)
{
await using var cmd = dataSource.CreateCommand("SELECT pg_notify('orders', $1)");
cmd.Parameters.Add(new() { Value = $"order {i} created" });
await cmd.ExecuteNonQueryAsync();
await Task.Delay(100);
}
});
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(1));
try
{
while (true)
await listener.WaitAsync(cts.Token); // returns after each notification
}
catch (OperationCanceledException)
{
Console.WriteLine("done listening");
}
[orders] order 1 created (from backend pid 18336)
[orders] order 2 created (from backend pid 18336)
[orders] order 3 created (from backend pid 18336)
done listening
pg_notify(channel, payload) is the function form of NOTIFY. Unlike NOTIFY, it accepts parameters. Notifications sent inside a transaction are delivered only after it commits. They aren't stored: if the listener is disconnected, it misses them. Use them to wake up workers, not as a durable queue.
Dapper
Dapper works with any DbConnection and removes the reader boilerplate. Npgsql arrays work as Dapper parameters too:
#:package Npgsql@10.0.3
#:package Dapper@2.1.89
#:property PublishAot=false
using Dapper;
using Npgsql;
const string ConnStr = "Host=localhost;Port=5432;Username=postgres;Password=secret;Database=shop";
await using var dataSource = NpgsqlDataSource.Create(ConnStr);
DefaultTypeMap.MatchNamesWithUnderscores = true; // created_at -> CreatedAt
await using var conn = await dataSource.OpenConnectionAsync();
int id = await conn.ExecuteScalarAsync<int>(
"INSERT INTO products (name, price, tags) VALUES (@Name, @Price, @Tags) RETURNING id",
new { Name = "Webcam", Price = 59.90m, Tags = new[] { "usb", "video" } });
Console.WriteLine($"new id: {id}");
var usb = await conn.QueryAsync<Product>(
"SELECT id, name, price, tags, created_at FROM products WHERE @Tag = ANY(tags) ORDER BY id",
new { Tag = "usb" });
foreach (var p in usb)
Console.WriteLine($"{p.Id}: {p.Name} {p.Price} [{string.Join(", ", p.Tags)}] {p.CreatedAt.Kind}");
var some = await conn.QueryAsync<string>(
"SELECT name FROM products WHERE id = ANY(@Ids) ORDER BY id", new { Ids = new[] { 1, 2, 4 } });
Console.WriteLine(string.Join(", ", some));
class Product
{
public int Id { get; init; }
public string Name { get; init; } = "";
public decimal Price { get; init; }
public string[] Tags { get; init; } = [];
public DateTime CreatedAt { get; init; }
}
new id: 4
1: Keyboard 49.99 [usb, office] Utc
2: Mouse 19.50 [usb, wireless] Utc
4: Webcam 59.90 [usb, video] Utc
Keyboard, Mouse, Webcam
PostgreSQL convention is snake_case column names. MatchNamesWithUnderscores maps them to PascalCase properties, but only for property setters. A positional record like record Product(int Id, ...) fails here, because Dapper matches constructor parameters by exact name and type (the text[] column comes back as System.Array).
Entity Framework Core
The EF Core provider is Npgsql.EntityFrameworkCore.PostgreSQL. Its major version follows EF Core. It translates LINQ over arrays, jsonb and full-text search into PostgreSQL SQL. The optional EFCore.NamingConventions package gives you snake_case table and column names:
#:package Npgsql.EntityFrameworkCore.PostgreSQL@10.0.3
#:package EFCore.NamingConventions@10.0.1
#:property PublishAot=false
using Microsoft.EntityFrameworkCore;
const string ConnStr = "Host=localhost;Port=5432;Username=postgres;Password=secret;Database=shop_ef";
var options = new DbContextOptionsBuilder<ShopContext>()
.UseNpgsql(ConnStr)
.UseSnakeCaseNamingConvention()
.Options;
await using var db = new ShopContext(options);
await db.Database.EnsureDeletedAsync();
await db.Database.EnsureCreatedAsync(); // use migrations in real apps
db.Books.AddRange(
new Book { Title = "Dune", Tags = ["sf", "classic"], Price = 9.99m },
new Book { Title = "Neuromancer", Tags = ["sf", "cyberpunk"], Price = 12.50m });
await db.SaveChangesAsync();
var cyberpunk = await db.Books
.Where(b => b.Tags.Contains("cyberpunk"))
.Select(b => b.Title)
.ToListAsync();
Console.WriteLine(string.Join(", ", cyberpunk));
var query = db.Books.Where(b => b.Title.StartsWith("D")).OrderBy(b => b.Price);
Console.WriteLine(query.ToQueryString());
public class ShopContext(DbContextOptions<ShopContext> options) : DbContext(options)
{
public DbSet<Book> Books => Set<Book>();
}
public class Book
{
public int Id { get; set; }
public required string Title { get; set; }
public List<string> Tags { get; set; } = [];
public decimal Price { get; set; }
}
Neuromancer
SELECT b.id, b.price, b.tags, b.title
FROM books AS b
WHERE b.title LIKE 'D%'
ORDER BY b.price
List<string> Tags became a native text[] column, and Tags.Contains("cyberpunk") was translated to WHERE 'cyberpunk' = ANY (b.tags), so no join table was needed. In ASP.NET Core, register the context with builder.Services.AddDbContext<ShopContext>(o => o.UseNpgsql(connStr)).
ASP.NET Core
For raw ADO.NET in a web app, the Npgsql.DependencyInjection package registers an NpgsqlDataSource as a singleton:
#:sdk Microsoft.NET.Sdk.Web
#:package Npgsql.DependencyInjection@10.0.3
#:property PublishAot=false
using Npgsql;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddNpgsqlDataSource(builder.Configuration.GetConnectionString("Default")!);
var app = builder.Build();
app.MapGet("/products/{id:int}", async (int id, NpgsqlDataSource db) =>
{
await using var cmd = db.CreateCommand("SELECT name FROM products WHERE id = $1");
cmd.Parameters.Add(new() { Value = id });
return await cmd.ExecuteScalarAsync() is string name
? Results.Ok(new { id, name })
: Results.NotFound();
});
app.Run();
GET /products/1 -> 200 {"id":1,"name":"Keyboard"}
GET /products/99 -> 404
Tips
- Create one
NpgsqlDataSourceper database and reuse it. Don't create one per request. - Prefer
$1positional parameters in hot paths, and= ANY($1)with an array instead of buildingINlists. - Use
timestamptzand UTCDateTimevalues. Npgsql refuses to write a localDateTimetotimestamptz. - Use
RETURNINGto get generated ids andON CONFLICTfor upserts instead of a select followed by an insert. - Match errors on
PostgresException.SqlStatewithPostgresErrorCodesconstants, not on message text, which can be localized. - Use
COPY(BeginBinaryImportAsync) to load thousands of rows. - Pass a
CancellationTokento the*Asyncmethods in server code. Npgsql cancels the query on the server when the token fires.Command Timeoutin the connection string sets the default time limit for each command.