English
Messages and attachments
Step 1. The message
Why. A message is the most numerous entity: a busy chat has hundreds of thousands of them. Its design follows from how messages are read and changed:
- The id is the cursor. History is loaded page by page: "the 50 messages before this one". Because the id is a UUIDv7, "before" is simply "with a smaller id", and the same id is the read position of
ChatMember.LastReadMessageId. - Replies point to another message of the same chat through
ReplyToMessageId, a nullable foreign key from the table of messages to itself — a self-referencing relationship. - Editing keeps the same message and records
EditedAt, so clients can show "edited". - Deleting is soft. The row stays and gets
DeletedAt; the service clears the text and removes the attachments (topic 11). If the row disappeared, replies to it would point nowhere and a read position equal to its id would be lost. Clients show "message deleted" instead.
Do.
cs
namespace Chatex.Data.Entities;
/// <summary>
/// A chat message. <see cref="Id"/> is a UUIDv7, so it sorts by creation time and doubles as the pagination cursor.
/// </summary>
public class Message : IHasCreatedAt
{
public Guid Id { get; set; } = Guid.CreateVersion7();
public Guid ChatId { get; set; }
public Guid SenderId { get; set; }
public required string Body { get; set; }
public Guid? ReplyToMessageId { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public DateTimeOffset? EditedAt { get; set; }
/// <summary>Soft delete: the row stays so replies and read positions keep pointing at it.</summary>
public DateTimeOffset? DeletedAt { get; set; }
public Chat Chat { get; set; } = null!;
public User Sender { get; set; } = null!;
public Message? ReplyTo { get; set; }
public ICollection<Attachment> Attachments { get; set; } = [];
}Body is required because a message without text cannot be created; an empty text after deletion is still a string, not null. The class implements IHasCreatedAt only: the edit time is set by the service, because only an edit of the text, not every change of the row, counts as "edited".
Step 2. The attachment
Why. How does a file get into a message? The obvious way — send the text and the file in one request — makes the request slow and fragile: a 20 MB upload that fails at 90 % loses the text too, and the user cannot see the upload progress of each file. Chatex uses the upload first, link later approach common in messengers:
- The client uploads the file on its own (
POST /api/attachments) as soon as the user picks it. The server stores it and creates anAttachmentwithMessageId = null— an upload that does not belong to any message yet. - When the user presses Send, the message request carries only the ids of the uploads. The service checks that they belong to the sender and are not used yet, and sets their
MessageId. - An upload that is never sent (the user closed the tab) stays without a message; an hourly cleanup deletes such uploads after 24 hours (topic 13).
Two more decisions protect the server:
StoragePathis generated by the server (2026/10/{guid}), never taken from the user. A file name like../../etc/passwdmust never become a path on disk (path traversal).FileNamekeeps the original name, but only to show it and to suggest it when the file is downloaded.
Do.
cs
namespace Chatex.Data.Entities;
/// <summary>
/// A file stored on disk. Uploaded first (with <see cref="MessageId"/> null), then linked to a message when it is sent.
/// </summary>
public class Attachment : IHasCreatedAt
{
public Guid Id { get; set; } = Guid.CreateVersion7();
public Guid? MessageId { get; set; }
public Guid UploaderId { get; set; }
/// <summary>Original client file name, for display only. Never used as a path.</summary>
public required string FileName { get; set; }
public required string ContentType { get; set; }
public long SizeBytes { get; set; }
/// <summary>Path relative to the uploads root, e.g. <c>2026/10/{guid}</c>.</summary>
public required string StoragePath { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public Message? Message { get; set; }
public User Uploader { get; set; } = null!;
}Message? is nullable here — unlike Chat = null! in Message — because an attachment really can exist without a message.
The tables we are aiming at
The model is complete. In topic 4 EF Core turns it into tables. Fig. 3.3 shows the key columns of the three chat tables as they will appear in PostgreSQL: the names in snake_case, the enumerations as strings, the composite key of chat_members.
Fig. 3.3. Key columns of the chat tables
Check
The data project now builds:
powershell
dotnet buildThe output ends with Build succeeded, 0 Warning(s), 0 Error(s), and Source/Chatex.Data/Entities contains ten files: Attachment.cs, Chat.cs, ChatMember.cs, ChatMemberRole.cs, ChatType.cs, Message.cs, RefreshToken.cs, Timestamps.cs, User.cs, UserProfile.cs.
Step 3. Try the model
Why. The build proves that the code compiles, not that the rules are right. The real tests come in topic 6, when the test infrastructure exists. Until then, a few lines of code can show the entities at work. .NET 10 can run a single .cs file without a project (a file-based app), and such a file can reference a project with the directive #:project.
Do. Create a folder outside your repository, for example D:\Work\Playground, so that the experiment does not end up in a commit and is not subject to the strict build settings of the repository. Create entities.cs in it; change the path in the first line if your repository is not in D:\Work\Chatex:
cs
#:project D:\Work\Chatex\Source\Chatex.Data\Chatex.Data.csproj
using Chatex.Data.Entities;
var alice = new User { UserName = "alice" };
var bob = new User { UserName = "bob" };
Console.WriteLine($"Alice: {alice.Id}");
Console.WriteLine($"Bob: {bob.Id}");
Console.WriteLine(Chat.MakeDirectKey(alice.Id, bob.Id));
Console.WriteLine(Chat.MakeDirectKey(bob.Id, alice.Id));
var subscriber = new ChatMember { Role = ChatMemberRole.Subscriber };
Console.WriteLine($"Subscriber posts in a channel: {subscriber.CanPost(ChatType.Channel)}");
Console.WriteLine($"Subscriber posts in a group: {subscriber.CanPost(ChatType.Group)}");
var token = new RefreshToken { TokenHash = "x", ExpiresAt = DateTimeOffset.UtcNow.AddDays(30) };
Console.WriteLine($"Active now: {token.IsActiveAt(DateTimeOffset.UtcNow)}");
Console.WriteLine($"Active in 31 days: {token.IsActiveAt(DateTimeOffset.UtcNow.AddDays(31))}");Run it from that folder:
powershell
dotnet run entities.csCheck
The output looks like this (your ids differ):
Alice: 01a1e0ce-526e-742b-8216-1fab814b067a
Bob: 01a1e0ce-526e-70b6-8fa8-8593af081b86
01a1e0ce526e70b68fa88593af081b86:01a1e0ce526e742b82161fab814b067a
01a1e0ce526e70b68fa88593af081b86:01a1e0ce526e742b82161fab814b067a
Subscriber posts in a channel: False
Subscriber posts in a group: True
Active now: True
Active in 31 days: False- Both ids start with the same digits: the time part, because the two users were created in the same millisecond. Here Bob's id happens to be smaller than Alice's although he was created later — within one millisecond the order is random.
- Both direct keys are equal, whichever user comes first.
- The subscriber may post in a group but not in a channel; the token is active now and expired after 31 days.
Try a few changes on your own: create a ChatMember with the role Admin and call CanPost(ChatType.Channel); set RevokedAt of the token and check IsActiveAt again; try to create new Message() without Body and read the compiler error.