English
From features to entities
Finding the entities
An entity is a thing the application must remember and tell apart from other things of the same kind by an identity, not by its values. Two messages with the same text are still two messages. A simple way to find the entities is to read the feature list of topic 1 and write down the nouns that must survive a restart of the server:
- a user who signs in with a name or an email and a password;
- the user's public profile: display name, bio, avatar;
- the refresh token that keeps a user signed in for 30 days;
- a chat — direct, group or channel;
- the membership of a user in a chat, with a role and the position up to which the user has read;
- a message in a chat, possibly a reply to another message;
- an attachment: a file uploaded with a message.
Other nouns of the feature list are not entities. "Online presence" and "typing" are short-lived states that live in memory (topic 14); an "unread counter" is computed from the read position; a "read receipt" is the read position seen by others.
Relationships
Fig. 3.2 shows the entities and how they are related. Read each line in both directions: a user has exactly one profile, and a profile belongs to exactly one user; a chat has zero or more members, and every member belongs to one chat.
Fig. 3.2. The entities of Chatex and their relationships
The interesting one is the many-to-many relationship between users and chats: a user is in many chats, and a chat has many users. It is not a direct link but an entity of its own, ChatMember, because the link carries data: the role, the join time, the read position, the "muted" flag.
In C#, a relationship is expressed twice:
- as a foreign key property that holds the id of the related entity:
Message.ChatId,Message.SenderId; - as a navigation property that holds the related object or collection:
Message.Chat,Chat.Messages. EF Core fills navigation properties when we ask it to load related data (topic 5).
Identifiers: UUIDv7
Every entity needs an identifier — a primary key. The two usual choices are an auto-incremented integer (1, 2, 3, …, assigned by the database) and a Guid (a random 128-bit value, assigned by the application). Chatex uses a third option, the UUID version 7, created by Guid.CreateVersion7() (.NET 9 and later).
A UUIDv7 starts with the current time in milliseconds, followed by random bits:
01a1e0ce-526e-742b-8216-1fab814b067a
└───────────┘ └───────────────────┘
milliseconds version, randomThis gives Chatex the advantages of both usual choices:
- like a random
Guid, the id is created in C# before the entity is saved, so a service can build a whole graph of related objects in memory and save them at once; ids from different servers or tests never clash; and an id says nothing about how many users or messages exist; - like an integer, the ids sort by creation time. This becomes important in topic 5: the id of a message is also its position in the history. "Load the 50 messages older than this one" is simply
id < x, and "the user has read everything up to this message" is one id. Sorted ids also keep the database index compact, because new rows go to its end.
Within one millisecond, the order of two ids is random. For a messenger that is not a problem: two messages sent in the same millisecond have no natural order anyway.
Why not DateTime as the sort key?
A timestamp is not unique: two messages can share it, and then "older than this one" is ambiguous. An id is unique by definition, and a UUIDv7 additionally carries the time.
Timestamps
Almost every entity records when it was created, and some record when they were last updated. We do not want every service to remember to set these times, and we want the tests to control the clock (a test of "a token expires after 30 days" cannot wait 30 days). So the times are set in one place: in topic 4 a component of EF Core, an interceptor, fills them in automatically just before saving.
For that, the interceptor needs a way to recognise the entities that have such times. Two small interfaces mark them.
Do. Create the folder Source/Chatex.Data/Entities and the first file in it:
cs
namespace Chatex.Data.Entities;
/// <summary>Creation time is stamped by <c>TimestampInterceptor</c> when the entity is first saved.</summary>
public interface IHasCreatedAt
{
DateTimeOffset CreatedAt { get; set; }
}
/// <summary>Update time is stamped by <c>TimestampInterceptor</c> on every insert and update.</summary>
public interface IHasUpdatedAt
{
DateTimeOffset UpdatedAt { get; set; }
}The <summary> comments are XML documentation comments: the IDE shows them when you hover over a type or a member, and <c> marks code inside the text. Chatex documents what is not obvious from the name, and the comments are part of the listings because they are part of the code you are reading.
Where rules belong
An entity in Chatex is mostly a set of properties that EF Core maps to columns. But some rules depend only on the data of one entity and are needed in several places:
- "may this member post in a chat of this type?" depends only on the member's role;
- "is this refresh token still valid at time t?" depends only on its expiry and revocation times;
- "what is the key of the direct chat between users A and B?" depends only on the two ids.
Such rules are methods of the entity itself: they are easy to find, easy to test and cannot be forgotten. Rules that need other data — "is the sender a member of this chat?", "is the handle already taken?" — need the database and belong to the services of Chatex.Core (module 3).
Anemic and rich domain models
A model whose entities have only properties is called anemic; one where entities enforce all their rules is called rich. Chatex chooses a middle way that fits EF Core well: public setters (EF Core and the services set the properties) plus methods for the self-contained rules. Larger domains often go further towards rich entities with private setters and constructors that enforce every invariant; EF Core supports both styles (see the C# course topic on EF Core for how it maps classes to tables).
The files of the model
The domain model consists of ten files in Source/Chatex.Data/Entities. We write them in three groups:
| Chapter | Files |
|---|---|
| Users, profiles and tokens | User.cs, UserProfile.cs, RefreshToken.cs |
| Chats and members | ChatType.cs, ChatMemberRole.cs, Chat.cs, ChatMember.cs |
| Messages and attachments | Message.cs, Attachment.cs |
The entities reference each other through navigation properties, so the project builds only when all of them exist. Do not worry about compiler errors such as "The type or namespace name Chat could not be found" while you are halfway through; the check comes at the end of the last chapter.