Hamsayeh Notes 4: Splitting a DbContext without losing the transaction

Hamsayeh Notes 4: Splitting a DbContext without losing the transaction

On 15 May, Hamsayeh's single AppDbContext stopped being the write path. Seven bounded contexts took over in one day, 37 repositories moved to them, and every command that had relied on one SaveChanges now wrote through several. Backend Notes 9 describes where the boundaries went and how they are guarded. This post stays with the cut itself: what it broke, what the repo does today, and what it cost in queries and migrations. Hamsayeh is in development and runs with Docker Compose and demo data, so the evidence here is commits and code.

What the split took away

The preparation started on 13 May, when EF configurations were grouped by schema. The split commit on 15 May touched 168 files. It removed cross-schema navigation properties from more than 15 entities, dropped Building.ChargeCycles, added a BuildingId column to Payment with a backfill, and created seven contexts with their own migration history. A second commit that day introduced CompositeUnitOfWork, which saved every dirty context in one call, one after another. Each save was its own transaction, so a failure in a later context left the earlier ones committed.

That lasted a day. On 16 May a commit titled "add shared transaction" gave all contexts one scoped connection. The class is 76 lines today, and this is its core, lightly simplified:

public async Task<int> SaveChangesAsync(CancellationToken ct = default)
{
    var changed = GetRegisteredContexts()
        .Where(ctx => ctx.ChangeTracker.HasChanges()).ToArray();
    if (changed.Length == 0) return 0;

    if (sharedConnection.GetType().Name != "NpgsqlConnection")
    {
        // SQLite: each context has its own connection, so save one by one
        var fallbackTotal = 0;
        foreach (var ctx in changed)
            fallbackTotal += await ctx.SaveChangesAsync(ct);
        return fallbackTotal;
    }

    if (sharedConnection.State != ConnectionState.Open)
        await sharedConnection.OpenAsync(ct);

    await using var tx = await sharedConnection.BeginTransactionAsync(ct);
    try
    {
        var total = 0;
        foreach (var ctx in changed)
        {
            await ctx.Database.UseTransactionAsync(tx, ct);
            total += await ctx.SaveChangesAsync(ct);
        }
        await tx.CommitAsync(ct);
        return total;
    }
    catch
    {
        await tx.RollbackAsync(ct);
        throw;
    }
    finally
    {
        foreach (var ctx in changed)
            await ctx.Database.UseTransactionAsync(null, ct);
    }
}

The other half is in registration. On PostgreSQL each context is built with UseNpgsql(sp.GetRequiredService<DbConnection>(), ...), so every context in a request scope holds the same NpgsqlConnection and one DbTransaction can cover them all. Seven contexts take part, in a fixed array with identity first. Audit and reporting stay outside it.

Where commands span two modules

Note 9 gives a habit for keeping a later split cheap: a command changes one module's data in one transaction. The code has not fully arrived there. The composite unit of work lets one call span contexts, and some handlers use that. Five of them write both building and accounting data: CreateBuilding, UpdateBuilding, CreateUnit, CreateUnitsBatch and UpdateUnit. Accounting keeps snapshot tables of buildings and units, and these handlers refresh them through IAccountingReferenceWriter just before the save (simplified):

unitRepository.Add(unit);                                       // building schema
await accountingReferenceWriter.UpsertUnitAsync(unit.Id, ...);  // accounting schema
await unitOfWork.SaveChangesAsync(ct);                          // one transaction on PostgreSQL

A new unit and its accounting snapshot commit together. That is convenient today, and it is the kind of write the note says would turn distributed if accounting ever moved out, so those five call sites are the first list to work through. The alternative, an event through an outbox, is not in place: the OutboxMessage table exists and nothing writes to it. Domain events are at a similar stage. The base class of the non-accounting contexts publishes them right after each context's save, which on this path comes before the shared commit, the timing problem Note 9 describes. A grep finds no INotificationHandler, so nothing acts on them yet.

Two bugs in three days

Two failures followed, both fixed inside the wizard commits from part 3. On 18 May, adding a brand-new board member failed with a foreign key violation from building_roles.UserId to identity.users.Id. The fix saves the user first (simplified):

if (user is null)
{
    user = User.Create(normalizedPhone, normalizedFullName, UserRole.User, clock.UtcNow);
    userRepository.Add(user);
    // Commit user first so the cross-schema FK from building_roles -> identity.users is satisfied.
    await unitOfWork.SaveChangesAsync(ct);
}

That use case now runs two transactions, so a failure on the role leaves the new user behind. The branch for an existing user commits UpdateProfile the same way before the overlap check, so as far as the code shows, a 409 there keeps the name change. A grep finds eight application files with more than one SaveChangesAsync call. That counts text matches, and in this handler two of them sit in exclusive branches, so I read it only as a list of places to check.

The history records the symptom and the fix and says little about the mechanism. The array already put identity before building at that commit, so save order does not obviously explain the violation. It also matters which database you look at. FK_building_roles_users_UserId comes from the legacy migration set. In the per-context migrations, no foreign key points outside its own schema, so on a fresh database the comment above guards a constraint that should not exist. That comes from reading migration files. No test in the repo runs the catalog query from Note 9.

On 19 May CreateUnit returned 500. The transaction had completed but stayed attached to the contexts, and the manager-contacts query that runs after the save hit it. The fix is the finally block above.

The API tests could not have caught that second bug. They run on SQLite through CustomWebApplicationFactory, which takes the sequential branch, and that branch never attaches a transaction. No test file mentions CompositeUnitOfWork, UseTransaction or Npgsql. The shared transaction, the reason the class exists, only runs when the Docker Compose stack does, and the Playwright suite that drives that stack arrived on 23 May, after both bugs. The commits do not say how either one was found.

What the read side paid

A query that used to join across domains can no longer do that. On 16 May GetBuildingActivitySummariesAsync was "decomposed into 6 separate per-context queries joined in memory, replacing a single cross-domain SQL query".

Payment history moved the other way on the same day. GetPaymentHistoryHandler had been loading up to 4,000 Payment aggregates with Include joins, mapping them all to DTOs, then filtering, sorting and paging in memory. The commit gives its reason: this "explodes as real building+unit+payment data grows". Now a query service in the accounting context does that work in the database, and the handler fetches building, unit and reviewer names for the page's rows only, about 20 (simplified):

var q = db.Payments.AsNoTracking();
if (buildingIds is not null)
    q = q.Where(p => buildingIds.Contains(p.BuildingId));
q = ApplySort(ApplyFilters(q, query), query);   // on the entity, before projecting

var total = await q.CountAsync(ct);
var items = await q
    .Skip((query.Page - 1) * query.PageSize)
    .Take(query.PageSize)
    .Select(p => new PaymentHistoryRow(p.Id, p.UnitId, p.BuildingId, /* ... */))
    .ToListAsync(ct);

The order matters: a comment in the file says that filtering on the projected row produces a subquery EF Core cannot translate.

The split removed a feature here, and the commit says so: "Cross-context text search (buildingName, unitNumber, reviewedByName) is not supported in the DB query." Search today covers receipt number, period label and rejection reason. The sort switch has no case for building or unit, so those keys fall back to newest first. Accounting's snapshot tables hold building names and unit numbers in the same context and could serve that search, but this query does not use them, and reviewer names have no snapshot. The repo holds no before and after timings, so I can describe what the query does differently and nothing about how much faster it is.

Three ways to reach a schema

The migration history had been rewritten once already. On 9 April, when entities received PostgreSQL schemas, 19 migration files became one InitialSchemas, in a commit that also carried other work and touched 112 files, removing about 30,000 lines. The set then grew under AppDbContext until the split gave each context its own InitialSchema. The commit message calls these no-op baselines, while the files create their tables. Reading the code, that is why one database cannot run both sets, and MigrationRunner has to choose:

private static bool ShouldMigrateContext(string contextName, bool hasLegacyAppMigrations)
{
    if (contextName == "AppDbContext") return hasLegacyAppMigrations;
    if (!hasLegacyAppMigrations) return true;

    return contextName is not "IdentityDbContext"
        and not "BuildingDbContext" and not "GovernanceDbContext"
        and not "GrowthDbContext" and not "ServiceDbContext"
        and not "MarketplaceDbContext";
}

The flag is true when public.__EFMigrationsHistory has rows. Each context migrates under a pg_advisory_lock, which keeps the two API hosts from migrating the same context at once. Development applies everything at startup, and the Production environment setting skips this and expects dotnet ef database update per context. The commit that added the runner "Removes the ambiguous conditional that silently skipped migration on Postgres."

The bookkeeping slipped within days. On 20 May IsOnboardingComplete went in through the App set, and a follow-up commit added the "missing BuildingDbContext migration". Until 3 June several changes appear twice, once in each set, for example AddOnboardingProgress and AddTicketVisibility. After that they go to the owning context only. Building has three later migrations, so as far as the code shows, a database on the legacy path would never receive them, because the runner skips that context there. Accounting went its own way: InitialAccountingSchema creates its tables fresh, with no copy step from the old finance schema. That is workable on demo data.

Route to a schemaApplies whenExercised by
Legacy App migrations (16 files)The public history table has rowsNo test or workflow in the repo
Per-context migrationsFresh PostgreSQLDocker Compose startup, so Playwright runs
EnsureCreatedSQLitexUnit API tests

The xUnit suite builds its schema from the model, a route no PostgreSQL database takes, and none of its tests applies a migration. PhoneNumberE164DataMigration.sql also sits in the Migrations folder as a manual script that nothing runs.

The next part leaves the database for the text stored in it: Persian strings that kept breaking, page direction, numerals and phone numbers.

This note is also available in Persian: read the Persian version.

Back to all notes