English
Topic 4. Entity Framework Core and PostgreSQL: the database context, configurations, interceptors and migrations
Goal: map the domain model to PostgreSQL tables with EF Core 10: a database context on top of ASP.NET Core Identity, one configuration class per entity with keys, lengths, indexes and delete rules, snake_case names, timestamps from an interceptor, and the first migration that creates the database.
Where we are
We stay in the data layer and connect the entities of topic 3 to the database (Fig. 4.1).
Fig. 4.1. EF Core connects the entities to PostgreSQL
- Starting point: topic 3 — the ten entities build; PostgreSQL runs in Docker (
docker compose up --detach --wait). - At the end of the topic the database
chatexhas 14 tables with their keys, indexes and constraints, created by a migration that is part of the repository, and./Run.ps1 dbbrings any computer to the same schema.
Steps
- The database context — EF Core and Npgsql packages ·
ChatexDbContexton top of Identity · table names - Configurations — the Fluent API · lengths and indexes · enumerations as strings · a check constraint · keys and delete rules
- Timestamps with an interceptor —
SaveChangesInterceptor·TimeProvider· stampingCreatedAtandUpdatedAt - The first migration — provider settings · the design-time factory ·
dotnet ef migrations add·database update· inspecting the tables - Checkpoint — what must work, self-check questions and exercises
Materials
- Course slides, part 2, Data: PostgreSQL and EF Core (slides "Fluent configuration", "UUIDv7 ids and keyset paging", "Timestamps and soft deletes", "Migrations from laptop to server")
ChatexDbContext.cs,Configurations/,TimestampInterceptor.csChatexDbContextFactory.cs,Migrations/Docs/DataModel.md– the data model and working with migrations- The C# course topic EF Core – the basics of EF Core