English
The first migration
Step 1. Provider settings in one place
Why. Two places will create a ChatexDbContext: the application (registered for dependency injection in topic 5) and the dotnet ef tool, which needs a context to read the model. Both must configure it identically — the same provider, the same naming convention, the same retry policy — or the tool would generate a schema the application does not expect. So the configuration lives in one method that both call.
Do. Create DependencyInjection.cs in the root of the data project. For now it contains only this method; in topic 5 the same class gets the registration of the whole data layer.
cs
using Microsoft.EntityFrameworkCore;
namespace Chatex.Data;
public static class DependencyInjection
{
internal static void Configure(DbContextOptionsBuilder options, string connectionString) =>
options.UseNpgsql(connectionString, npgsql => npgsql.EnableRetryOnFailure()).UseSnakeCaseNamingConvention();
}UseNpgsqlselects the PostgreSQL provider with the given connection string.EnableRetryOnFailuremakes EF Core repeat a command that failed for a transient reason — a dropped connection, a database restart, a failover. Without it, a database that is unavailable for two seconds turns into errors for every user who happened to send a message in those two seconds. The retries have a price for transactions, which topic 5 pays.UseSnakeCaseNamingConventioncomes fromEFCore.NamingConventions:LastActivityAtbecomeslast_activity_at,ChatMembersbecomeschat_members, the primary key ofchatsbecomespk_chats.
Step 2. A context for the tools
Why. To create a migration, dotnet ef loads our project, creates the context and reads its model. Usually the tool gets the context from the application's dependency injection, by running the startup project. We have no working application yet, and even later it is better if creating a migration does not depend on starting the API with all its settings. A class that implements IDesignTimeDbContextFactory<T> tells the tool how to create the context directly.
Do.
cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
namespace Chatex.Data;
/// <summary>Used by <c>dotnet ef</c> only. Reads the connection string from the CHATEX_DB environment variable.</summary>
internal sealed class ChatexDbContextFactory : IDesignTimeDbContextFactory<ChatexDbContext>
{
private const string DevConnectionString = "Host=localhost;Port=5432;Database=chatex;Username=postgres;Password=postgres";
public ChatexDbContext CreateDbContext(string[] args)
{
var connectionString = Environment.GetEnvironmentVariable("CHATEX_DB") ?? DevConnectionString;
var options = new DbContextOptionsBuilder<ChatexDbContext>();
DependencyInjection.Configure(options, connectionString);
return new ChatexDbContext(options.Options);
}
}The connection string comes from the environment variable CHATEX_DB, and without it falls back to the development database from compose.yaml. The ?? operator returns its left operand unless it is null. Set it when a tool must work with another database; a developer does not need to set anything. CI does not need it either: the check for missing migrations compares the model with the snapshot without a database (topic 22), and on the server the migrations bundle receives its connection string as an argument (topic 24).
The factory is internal: only the tool, which finds it by reflection, uses it.
Step 3. Create the migration
Why. A migration is a C# class that describes one change of the schema: Up applies it, Down reverts it. EF Core compares the current model with a snapshot of the model at the last migration and generates the code for the difference. Migrations are part of the repository, so every developer, the CI and the production server bring their databases to the same schema in the same steps (Fig. 4.2).
Fig. 4.2. The path of a schema change
Do. Make sure PostgreSQL runs (docker compose up --detach --wait), then create the first migration from the repository root:
powershell
dotnet ef migrations add InitialCreate --project Source/Chatex.Data --output-dir MigrationsThe tool builds the project, creates the context with the factory and writes three files to Source/Chatex.Data/Migrations:
| File | Content |
|---|---|
<timestamp>_InitialCreate.cs | the migration: Up creates the 14 tables with their keys, indexes and constraints, Down drops them |
<timestamp>_InitialCreate.Designer.cs | the model as it was at this migration (metadata, never edited) |
ChatexDbContextModelSnapshot.cs | the current model; the next migrations add compares against it |
The timestamp is the current time, so your file names differ from the reference (20261029094940_InitialCreate.cs); the content must be the same. Open the migration and find the chats table — every decision of the configurations is visible:
cs
migrationBuilder.CreateTable(
name: "chats",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
type = table.Column<string>(type: "character varying(16)", maxLength: 16, nullable: false),
title = table.Column<string>(type: "character varying(128)", maxLength: 128, nullable: true),
// ...
direct_key = table.Column<string>(type: "character varying(65)", maxLength: 65, nullable: true),
created_by_id = table.Column<Guid>(type: "uuid", nullable: false),
// ...
deleted_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("pk_chats", x => x.id);
table.CheckConstraint("ck_chats_direct_key", "(type = 'Direct') = (direct_key IS NOT NULL)");
table.ForeignKey(
name: "fk_chats_users_created_by_id",
column: x => x.created_by_id,
principalTable: "users",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
});and further down the index for history pages:
cs
migrationBuilder.CreateIndex(
name: "ix_messages_chat_id_id",
table: "messages",
columns: new[] { "chat_id", "id" },
descending: new[] { false, true });Always read a generated migration
The tool writes what the model says, not what you meant. A renamed property, for example, appears as "drop the column, add a new one" — and the data of the old column is lost. Read every migration before you commit it; fix the model and run dotnet ef migrations remove to try again.
The .editorconfig from topic 2 marks the folder Migrations as generated code, so the analyzers do not complain about the style of the generated files.
Step 4. Apply it
Do.
powershell
dotnet ef database update --project Source/Chatex.DataThe tool connects to the database, creates the table __EFMigrationsHistory, runs Up of every migration not listed there yet, and records it. Running the command again does nothing: the migration is already applied.
Check
List the tables:
powershell
docker compose exec postgres psql -U postgres -d chatex -c '\dt'The list has 14 tables: __EFMigrationsHistory, attachments, chat_members, chats, messages, refresh_tokens, role_claims, roles, user_claims, user_logins, user_profiles, user_roles, user_tokens, users. Then describe one of them:
powershell
docker compose exec postgres psql -U postgres -d chatex -c '\d chats'The output shows the columns with their types (character varying(16), timestamp with time zone), the indexes pk_chats, ix_chats_direct_key and ix_chats_public_handle (both UNIQUE), the check constraint ck_chats_direct_key and the foreign key to users with ON DELETE RESTRICT.
Step 5. See a constraint at work
Why. The check constraint and the unique indexes protect the data even from code that has bugs. Let us try to break the rule "only direct chats have a direct key" by hand.
Do. Open an interactive psql session:
powershell
docker compose exec postgres psql -U postgres -d chatexInsert a user (only the columns that may not be NULL; uuidv7() is a function of PostgreSQL 18) and try to give a group a direct key:
sql
insert into users (id, user_name, access_failed_count, email_confirmed, lockout_enabled,
phone_number_confirmed, two_factor_enabled, created_at)
values (uuidv7(), 'alice', 0, false, false, false, false, now());sql
insert into chats (id, type, title, direct_key, created_by_id, created_at, updated_at, last_activity_at)
select uuidv7(), 'Group', 'Wrong', 'a:b', id, now(), now(), now() from users where user_name = 'alice';Check
The second insert fails:
ERROR: new row for relation "chats" violates check constraint "ck_chats_direct_key"The same insert without direct_key succeeds. Clean up and leave psql:
sql
delete from chats; delete from users;sql
\qStep 6. Keep the model and the migrations in sync
Why. A developer may change an entity and forget to add a migration. The code builds, the tests may even pass locally against an old database — and the server breaks after the deploy. EF Core can detect this: it compares the model with the snapshot.
Do.
powershell
dotnet ef migrations has-pending-model-changes --project Source/Chatex.DataCheck
The command prints No changes have been made to the model since the last migration. Now add a property public string? Note { get; set; } to Chat, build and run the command again: it reports changes and exits with an error code — exactly what the CI of topic 22 checks on every push. Remove the property again.
Two commands of Run.ps1 from topic 2 work now:
./Run.ps1 dbstarts PostgreSQL and applies the migrations — the one command a new developer needs after cloning;./Run.ps1 migration <Name>adds a migration with the right options.