English
The database context
Step 1. Add the EF Core packages
Why. Entity Framework Core (EF Core) is an object-relational mapper: it translates between C# objects and rows of a relational database. We describe the tables once, in C#, and EF Core generates the SQL to create them, to query them with LINQ and to save changes. EF Core itself does not know any particular database; a provider adds that knowledge. Chatex needs three packages:
Npgsql.EntityFrameworkCore.PostgreSQL— the PostgreSQL provider (Npgsql is the .NET driver for PostgreSQL). The Identity package from topic 3 already brought EF Core itself;EFCore.NamingConventions— PostgreSQL folds unquoted names to lower case, so the C# nameLastActivityAtwould have to be written"LastActivityAt"with quotes in every hand-written query. This package names tables and columns in snake_case (last_activity_at), the usual style of PostgreSQL;Microsoft.EntityFrameworkCore.Design— the code that thedotnet eftool runs inside our project to create migrations. It is needed only at design time.
Do.
powershell
dotnet add Source/Chatex.Data package Npgsql.EntityFrameworkCore.PostgreSQLpowershell
dotnet add Source/Chatex.Data package EFCore.NamingConventionspowershell
dotnet add Source/Chatex.Data package Microsoft.EntityFrameworkCore.Designxml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
</ItemGroup>
</Project>dotnet add wrote the Design reference with two extra elements. PrivateAssets all means the package does not flow to the projects that reference Chatex.Data: Chatex.Core and Chatex.Api do not need the migration tooling, and it never ends up in the published application.
Step 2. The context
Why. A DbContext is the central class of EF Core. It holds the model — the list of entities and how each maps to a table — and it is a unit of work: it tracks the objects loaded through it, and SaveChangesAsync writes all their changes to the database in one go.
Chatex derives its context not from DbContext but from Identity's IdentityDbContext<TUser, TRole, TKey>. That base class already maps the account tables Identity needs: users, roles, the claims, external logins and tokens of users. The three type arguments say that our user class is User, roles use Identity's own IdentityRole<Guid>, and every key is a Guid.
Do. Create the context in the root folder of the data project:
cs
using Chatex.Data.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Chatex.Data;
public class ChatexDbContext(DbContextOptions<ChatexDbContext> options)
: IdentityDbContext<User, IdentityRole<Guid>, Guid>(options)
{
public DbSet<UserProfile> UserProfiles => Set<UserProfile>();
public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();
public DbSet<Chat> Chats => Set<Chat>();
public DbSet<ChatMember> ChatMembers => Set<ChatMember>();
public DbSet<Message> Messages => Set<Message>();
public DbSet<Attachment> Attachments => Set<Attachment>();
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Identity maps to AspNet* tables; use plain names instead. Principal tables (users, roles) are
// renamed first, because the snake_case convention names a foreign key when its dependent table is renamed.
builder.Entity<User>().ToTable("users");
builder.Entity<IdentityRole<Guid>>().ToTable("roles");
builder.Entity<IdentityUserRole<Guid>>().ToTable("user_roles");
builder.Entity<IdentityUserClaim<Guid>>().ToTable("user_claims");
builder.Entity<IdentityUserLogin<Guid>>().ToTable("user_logins");
builder.Entity<IdentityUserToken<Guid>>().ToTable("user_tokens");
builder.Entity<IdentityRoleClaim<Guid>>().ToTable("role_claims");
builder.ApplyConfigurationsFromAssembly(typeof(ChatexDbContext).Assembly);
}
}Line by line:
- The primary constructor
ChatexDbContext(DbContextOptions<ChatexDbContext> options)(C# 12) receives the options — the provider, the connection string, the interceptors — and passes them to the base class. The context itself does not know where the database is; whoever creates it decides (the application in topic 5, thedotnet eftool in The first migration). DbSet<T>properties are the entry points for queries:db.Messages.Where(...). They are written as expression-bodied properties that returnSet<T>(), so they never need an initial value and are nevernull.Usersis inherited fromIdentityDbContext.OnModelCreatingbuilds the model.base.OnModelCreatingmust come first: it maps the Identity tables, and our changes override its choices.- The
ToTablecalls rename Identity's tables. By default they are calledAspNetUsers,AspNetRoles, …; with snake_case they would becomeasp_net_users. Plain names such asusersread better in SQL. The order matters, as the comment explains: the snake_case convention names a foreign key constraint after its tables at the moment the dependent table is renamed, so the principal tables come first. ApplyConfigurationsFromAssemblyfinds every class in this assembly that implementsIEntityTypeConfiguration<T>and applies it. Each entity gets its own small configuration class (next chapter) instead of one endlessOnModelCreating.
Convention, configuration, annotation
EF Core builds the model in three layers. Conventions decide the default: a property named Id is the key, ChatId together with a Chat navigation is a foreign key, string? is a nullable column. Data annotations — attributes such as [MaxLength(64)] on the entity — change the default. The Fluent API in OnModelCreating or in configuration classes changes it too and has the last word. Chatex uses conventions plus the Fluent API only, so the entities of topic 3 stay plain classes with no database attributes.
Check
powershell
dotnet buildThe build succeeds. The model is not complete yet — the composite key of ChatMember and the key of UserProfile cannot be found by convention — but EF Core checks the model only when it is first used, in The first migration.