Leanpub Header

Skip to main content

The Entity Framework Core & PostgreSQL Handbook

Mastering EF Core 10 with PostgreSQL 18 for Production-Grade Applications

The Entity Framework Core & PostgreSQL Handbook

Your ORM works until it doesn't: a query returns ten thousand duplicated rows, a migration refuses a partitioned table, or the feature the product needs is one PostgreSQL has had for years. Twenty-one chapters that close the gap — LINQ translation, query plans, JSONB, full-text search, PostGIS and pgvector, then auditing, multi-tenancy and deployment. Every listing run against a live database. Every output captured, never typed.

Minimum price

$36.99

$48.99

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

Buying multiple copies for your team? See below for a discount!

PDF
EPUB
About

About

About the Book

Most Entity Framework Core material treats the database as a detail the provider will handle. Configure a DbContext, write LINQ, call SaveChanges. For a surprising amount of work that is exactly right, and it is why EF Core is worth using. It stops being right at the moment your application gets big enough to matter: when a query that looked innocent returns ten thousand duplicated rows, when a migration will not apply to a partitioned table, when two writers race and one silently wins, or when the feature the product needs is a capability your database has had for years and your ORM has never mentioned to you.

The Entity Framework Core & PostgreSQL Handbook closes that gap. Twenty-one chapters take you from a pooled DbContext and a deliberate primary-key decision to row-level security, PostGIS geography, and semantic search with pgvector — all on the stable surface of EF Core 10.0.11, the Npgsql provider 10.0.3, PostgreSQL 18.6, .NET 10 LTS, and C# 14.

You will learn how to:

Configure six pooled contexts, compiled models, and configuration that scales past a single file

Map C# onto PostgreSQL types deliberately — UUIDv7 keys, citext, arrays, ranges, enums, jsonb

Write migrations EF Core cannot scaffold for you, including partitioned tables

Read a query plan with EXPLAIN and choose the index the access pattern actually needs

Stop the cartesian explosion that makes one loading strategy a trap

Paginate by keyset instead of OFFSET, and benchmark the difference at a million rows

Store user-defined fields as JSONB and index them so the queries stay fast

Build full-text search with generated tsvector columns, ranking, trigrams and fuzzy matching

Make double-booking impossible with a tstzrange exclusion constraint

Query geography with PostGIS, and rank by meaning with pgvector and HNSW

Fuse full-text ranking and vector similarity into one hybrid query

Turn interceptors into an audit trail, and enforce tenant isolation in two layers that are tested against each other

Test against a real PostgreSQL with Testcontainers, deploy through a migration mid-flight, and publish events with the outbox and change-data capture

Along the way you build LuminaWork, a multi-tenant project and field-service platform: a modular monolith with six bounded contexts, six schemas, sixteen tables and thirteen chapter-labelled migrations, carrying a million work items under real indexing pressure by Chapter 7.

What makes this book different is that almost none of it was typed. Every SQL listing was executed against a live PostgreSQL 18.6 database by an automated harness — including the ones meant to fail, which are asserted to fail with exactly the error code the prose predicts. Every C# listing is an excerpt of compiling code, diffed against the companion repository before the book will build. Every output panel was captured from a real run rather than retyped, and every benchmark table renders from committed BenchmarkDotNet artifacts. The seeder uses no random number generator at all, so when you run a listing you get the printed output: the same rows in the same order, and the same plan shape, on your machine.

That adds up to 526 listings — 202 in C#, 116 in SQL, 109 panels of captured output, and 99 of configuration — plus 67 figures and 63 exercises, three per chapter in Basic, Intermediate and Challenge tiers, each with a starter project and a working solution.

Written for .NET developers who already use EF Core. If you can model an entity, write a LINQ query and add a migration, you are ready; no PostgreSQL background is assumed. Coming from SQL Server? Appendix D is the full translation guide, written after the other twenty chapters so it could be honest about what the book had actually run.

The companion code lives at https://github.com/RachidD68/the-entity-framework-core-and-postgresql-handbook — MIT licensed, one solution of 18 projects plus 42 exercise projects, and twenty-one git tags so any listing can be read at the state its chapter printed it.

Team Discounts

Team Discounts

Get a team discount on this book!

  • Up to 3 members

    Minimum price
    $86.00
    Suggested price
    $114
  • Up to 5 members

    Minimum price
    $135
    Suggested price
    $179
  • Up to 10 members

    Minimum price
    $259
    Suggested price
    $343
  • Up to 15 members

    Minimum price
    $369
    Suggested price
    $489
  • Up to 25 members

    Minimum price
    $555
    Suggested price
    $735

Bundle

Bundles that include this book

Author

About the Author

Rachid DAHIR

I design systems for the long haul.

As a software architect, technical author, and educator based in Morocco, I've spent more than a decade building enterprise-grade .NET solutions in financial services, healthcare, and large-scale enterprise environments — where reliability, performance, and clean architecture are not optional.

I write for developers who are ready to move past tutorials. My books share a deliberate standard: production-grade code only — no toy examples, no shortcuts that would never survive a code review; every concept explained, demonstrated, then practiced; every advanced topic taught with the same patience as an introductory one — because complexity is never an excuse for a poor explanation.

Whether you're a mid-career developer leveling up, a solution architect consolidating best practices, or an enterprise team standardizing modern .NET, my goal stays the same: clarity without compromise.

When I'm not writing code or prose, I explore mathematics, AI research, and natural health.

Contents

Table of Contents

Front Matter

  • Preface
  • Introduction
  • About the Author

Part I — Intermediate Core Concepts

  1. Setting the Stage with EF Core 10 and PostgreSQL 18
    • What EF Core 10 shipped
    • What PostgreSQL 18 means for your EF Core code
    • Npgsql: the driver, the provider, and one version rule
    • Meet LuminaWork
    • The book environment: one container, one volume, one port
    • Project setup: the toolchain, the pins, the connection
    • First connection, and how this book runs
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  2. Advanced DbContext and Model Configuration
    • Six contexts, one database
    • The life of a context
    • Three ways to configure one model
    • Conventions at scale
    • One entity, one configuration class
    • Shadow properties and backing fields
    • Value converters — and the comparers they owe you
    • The milestone: a model ready to become a schema
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  3. PostgreSQL Mapping Strategies
    • Naming: what the convention promised, the DDL delivers
    • The core entities on the page
    • A working tour of PostgreSQL's column types
    • Value generation: the decision matrix
    • Generated columns: virtual by default, stored by choice
    • Owned entities, complex types, and table splitting
    • The milestone: two migrations and a live schema
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  4. Relationships and Inheritance
    • One-to-many, done right
    • Many-to-many: name the join
    • One-to-one and the module boundary
    • Cascade behavior: two rulebooks, one graph
    • Inheritance mapping: TPH, TPT, TPC
    • Choosing TPH for task kinds
    • Owned types, JSONB, or a table of its own
    • The milestone: the graph goes live
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  5. Migrations and Schema Management
    • Inside a scaffolded migration
    • When the differ runs out of vocabulary
    • The migration EF cannot write for you
    • Scripts, bundles, and the machine that has no source tree
    • EF Core 10's per-migration transaction
    • Seeding: three answers, and the one this book runs
    • Zero downtime: expand, then contract
    • The milestone: the pipeline, end to end
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next

Part II — Querying and Performance

  1. Advanced LINQ Translation
    • What happens between your LINQ and PostgreSQL
    • The ritual, and the operator that finally retires it
    • Where joins come from, and what grouping becomes
    • One runtime list, three translations
    • The translations you only get on PostgreSQL
    • Where the query stops being SQL
    • The milestone: the whole feed, translated
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  2. Performance Tuning with PostgreSQL 18
    • The lab bench: a million rows and a fixed floor
    • Reading an execution plan
    • Indexes answer questions
    • Smaller, denser, smarter
    • Beyond B-tree: GIN, GiST and BRIN
    • Skip scans, and what they are not
    • Asynchronous I/O, and why sequential scans changed
    • Partitions at volume, and the index that summarizes storage
    • Naming your queries before you need to
    • Cancellation, and the retry that changes what a transaction means
    • The index pass, measured
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  3. Efficient Loading Patterns
    • Three ways to ask for related data
    • One query, or several
    • Narrow the question instead
    • Pagination, and the cliff at page ten thousand
    • Keyset pagination: ask for the next page, not the nth
    • Offset against keyset, measured
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  4. Advanced Query Techniques
    • Four ways out, and where each one lands
    • Raw SQL, safely
    • Calling PostgreSQL's own functions
    • Two filters, two names, one entity
    • Compiled queries, and the caches around them
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  5. Bulk Operations and Concurrency
    • One statement instead of forty thousand
    • What the statement gives back
    • The update that vanished
    • Transactions you decide about
    • Deadlocks, and what is safe to retry
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next

Part III — PostgreSQL Superpowers

  1. JSON and Semi-Structured Data
    • The fields you did not design
    • Three routes into one column
    • Reaching inside from LINQ
    • Making it fast: GIN over a document
    • Document, complex type, or columns
    • Reading it back out
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  2. Full-Text Search and Advanced Text
    • The full-text model
    • Designing search.search_document
    • Full-text search from LINQ
    • When the words are wrong: pg_trgm
    • citext, ILIKE, and unaccent
    • Where lexical search stops being enough
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  3. Arrays, Ranges, and Specialized Types
    • The tags column, finally explained
    • Querying arrays: three questions, two operators, one index
    • Ranges: a time window is one value
    • FieldOps is born: one migration, one theorem
    • Native enums, and what they cost
    • Composite types and domains
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  4. Geospatial Data with PostGIS
    • PostGIS and the NetTopologySuite plugin
    • Geometry versus geography
    • The migration, and the backfill it owes
    • Proximity and containment, from LINQ
    • The spatial index: GiST, second time in anger
    • The milestone: tasks near me
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  5. Vector Search and Embeddings with pgvector
    • From matching words to measuring meaning
    • The plugin, the column, and the migration that was already applied
    • Where the vectors come from
    • Distance functions, from LINQ
    • The HNSW index, and recall you must measure
    • Hybrid search: fusing words and meaning
    • Where this book stops
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next

Part IV — Production Architecture and Operations

  1. Interceptors, Diagnostics, and Logging
    • The interception surface
    • Command interceptors: the slow-query log you own
    • Connection interceptors: identity at the moment of opening
    • Transaction and SaveChanges interceptors
    • Diagnostic listeners: observation without registration
    • Structured logging: Serilog, categories, and the redacted line
    • OpenTelemetry: spans and meters
    • The milestone: one composition root, two profiles
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  2. Temporal Data and Auditing
    • Two kinds of time
    • Application time in the schema: PostgreSQL 18's temporal constraints
    • The audit trail: giving the skeleton a table
    • Entity history and point-in-time reads
    • Soft delete, completed
    • The set-based gap: auditing what the tracker never sees
    • Row versioning — and why xmin is not history
    • Practical system-versioned data: the decision framework
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  3. Multi-Tenancy and Security
    • Three ways to keep tenants apart
    • Layer one: named query filters, and where they stop
    • Resolving the tenant: requests, jobs, and the connection
    • Layer two: row-level security
    • Defense in depth is a testable claim
    • Direct access without shared passwords: PostgreSQL 18's OAuth
    • Operating shared tables: migrations, exports, erasure
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  4. Testing and Integration Testing
    • What the in-memory provider is actually testing
    • A real PostgreSQL, started by the test run
    • Migrate, seed, and the reset that makes it affordable
    • The suite as a tour of the book
    • Testing the migrations themselves
    • Proving resilience: an execution strategy under a dropped connection
    • What runs on every push
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  5. Deployment, CI/CD, and DevOps
    • What a release actually is
    • Two images, and the one that must not carry a compiler
    • Kubernetes, and the ranking nobody enjoys hearing
    • Who runs the migrations, and when
    • Two pools, and the line where your session stops being yours
    • Retry, and the decision the last chapter left you
    • The I/O knobs, and the column that says what changing one costs
    • Watching from the server side, and knowing the pod is alive
    • Backups, and the rehearsal that makes them real
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next
  6. Microservices and Event-Driven Patterns
    • Six schemas, six services waiting
    • The dual write, and the table that fixes it
    • The dispatcher, and the query that makes it safe to run twice
    • Waking the dispatcher without polling
    • An event store on jsonb, and the projection it feeds
    • Change data capture, and the setting that has been waiting since Chapter 1
    • Choosing between them
    • What you now operate
    • Summary
    • Key Terms
    • Practice Exercises
    • What's Next

Appendices

  • Appendix A — Npgsql Provider Reference for EF Core 10
  • Appendix B — PostgreSQL 18 SQL Features Quick Reference
  • Appendix C — EF Core 10 API Changes and Migration Guide
  • Appendix D — SQL Server to PostgreSQL Translation Guide
  • Appendix E — LuminaWork Architecture and Repository Guide
  • Other Books You’ll Enjoy
  • Keyword Index

Get the free sample chapters

Click the buttons to get the free sample in PDF or EPUB, or read the sample online here

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

In fact, authors have earned over $15 million writing, publishing and selling on Leanpub.

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub