English
Checkpoint
What must work
powershell
dotnet buildpowershell
dotnet format Chatex.slnx --verify-no-changesEvery file of the data layer is now final. Compare the whole project with the reference; only the migration file names and the order of the package references may differ:
powershell
git diff --no-index --stat Source/Chatex.Data D:\Work\Chatex-Reference\Source\Chatex.DataCommit:
powershell
git add .powershell
git commit -m "Add repositories, unit of work, keyset paging and file storage"Common mistakes
Table 5.1. Common mistakes in the repositories
| Symptom | Cause | Fix |
|---|---|---|
the playground fails with DbUpdateException at SaveChangesAsync on its second run | the users from the first run still exist, so the new ones are not created and the chat refers to a missing user | empty the tables with truncate users cascade; |
The configured execution strategy 'NpgsqlRetryingExecutionStrategy' does not support user-initiated transactions | a transaction was begun with BeginTransactionAsync outside an execution strategy | use IUnitOfWork.ExecuteInTransactionAsync |
Model building is not supported when publishing with NativeAOT in the playground | file-based programs use Native AOT by default | add #:property PublishAot=false |
Cannot access a disposed context instance | a repository from one scope is used after the scope ended | resolve services from the scope you are in; one scope per unit of work |
a related entity is null after a query | the navigation property was not loaded | add Include(...) or project into a new type |
| changes to an entity are not saved | the entity came from an AsNoTracking query | load it with a tracked method (GetByIdAsync) before changing it |
a search for _ returns every user | the search text is used as a pattern without escaping | build the pattern with LikePattern.Contains and pass LikePattern.Escape |
| the second history page repeats messages | the cursor was taken from the extra row, or Take(limit) was used | take limit + 1 and let Paging.ToPage drop the extra row |
Self-check questions
- What does Chatex gain from repositories, although
DbContextalready implements Repository and Unit of Work? - Which repository methods write immediately, and which wait for
SaveChangesAsync? Why are both kinds needed? - What do
Include,AsNoTrackingandAsSplitQuerydo? When would you use each? - Why does
UnitOfWorktranslate a unique violation intoUniqueConstraintException? Why does it clear the change tracker? - Why does an explicit transaction have to run inside an execution strategy when retries are on? What does that mean for the code inside the lambda?
- What are the two problems of offset paging in a messenger, and how does keyset paging solve them?
- Why does the history query fetch
limit + 1rows? - Why is the chat list cursor a pair of values, and how does PostgreSQL compare
(a, b) < (x, y)? - How does
MarkReadAsyncguarantee that a read position never moves backwards, even with two browser tabs? - What is the N+1 problem, and how does
GetUserChatsAsyncavoid it? - How does
LocalFileStorageprevent path traversal? Name both defences. - Which services of the data layer are singletons and which are scoped? What would break if
ChatexDbContextwere a singleton? - Why does the database health check bypass the retry policy?
Exercises
See the SQL. In a copy of
data.cs, add the line#:package [email protected]after the other directives andusing Microsoft.Extensions.Logging;, and replaceservices.AddLogging();withcsservices.AddLogging(logging => logging.AddConsole() .AddFilter("Microsoft.EntityFrameworkCore.Database.Command", LogLevel.Information));Run it on an emptied database and find the SQL of the chat list: the
count(*)sub-query of the unread counter and theROW_NUMBER()that picks the last message. How many SQL statements does one history page take, and why (hint:AsSplitQuery)?Search. Extend the playground: create a public channel with the handle
dotnet_newsand the title "Dotnet news", then callSearchPublicAsync("_news", 10)andSearchPublicAsync("NEWS", 10). Explain both results.Catch-up. Call
GetPageAsyncwithafterset to the id of the second message and limit 2. In which order do the messages come back, and why is that the right order for filling a gap after a reconnect?A race. Run two copies of a program at the same time that both try to create the direct chat between Alice and Bob. Which exception does the loser get, and with which
ConstraintName?