In an ASP.NET Core modular monolith on EF Core 10, why give each module its own DbContext and schema, and how do modules then read each other's data?
answer
- one model per module
- HasDefaultSchema("fees")
- MigrationsHistoryTable per context
- no LINQ join across two contexts
- ask the owning module's contract
basics
~20 sA DbContext per module, with HasDefaultSchema and its own migrations history table, keeps each module's tables and migrations private and extractable. Other modules never query those tables; they call the owning module's public contract or keep their own copy updated by events.
solid answer
~40 sEach module registers its own context, `FeesDbContext`, `AdmissionsDbContext`, in its `AddX` method, and its `OnModelCreating` calls `modelBuilder.HasDefaultSchema("fees")` so its tables live in one schema of the shared database. The migrations history table does **not** follow the model's default schema; set `MigrationsHistoryTable("__EFMigrationsHistory", "fees")` on the provider options so each module keeps its own history. Migrations are then added per context with `--context`. The payoff: a module's tables have exactly one writer, and moving it to its own database later is mostly a data copy and a connection-string change. The cost is cross-module reads. A LINQ query over sets from two context instances throws `InvalidOperationException` ("Cannot use multiple context instances within a single query execution"). So Timetabling asks Admissions through a public interface such as `IAdmissionsModule.GetEnrolledStudentsAsync`, or keeps a local read copy updated by Admissions' events.
code
csharp · 16 linesinternal sealed class FeesDbContext(DbContextOptions<FeesDbContext> options) : DbContext(options)
{
public DbSet<Invoice> Invoices => Set<Invoice>();
public DbSet<Payment> Payments => Set<Payment>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("fees");
modelBuilder.ApplyConfigurationsFromAssembly(typeof(FeesDbContext).Assembly);
}
}
// inside AddFeesModule
services.AddDbContext<FeesDbContext>(o => o.UseNpgsql(
config.GetConnectionString("university"),
npgsql => npgsql.MigrationsHistoryTable("__EFMigrationsHistory", "fees")));go deeper
Know that each module can have its own DbContext, and that a schema per module keeps its tables apart in one database.
Explain HasDefaultSchema, why the migrations history table needs its own setting, and how dotnet ef selects a context with --context.
Show how modules read each other's data without shared tables, why a cross-context LINQ query fails, and when a cross-context transaction is acceptable.
Decide when a module moves from its own schema to its own database, and how data ownership rules are reviewed as modules and teams grow.
## Why one context per module In a university modular monolith, Admissions, Fees and Timetabling share one host and usually one PostgreSQL database. Giving each its own `DbContext` is how EF Core expresses data ownership: - **One model per module.** `FeesDbContext` maps invoices and payments; it has no `DbSet` for applicants. A Fees developer cannot write a join to the admissions tables, because those entities are not in the model. - **One writer per table.** Only the owning module's context writes its tables, so rules about that data live in one place. - **Independent migrations.** Each context has its own migrations folder and model snapshot, so teams stop colliding on one shared snapshot file. - **Extractable.** Moving Fees to its own database later means copying its schema and changing its connection string, not untangling foreign keys across modules. ## Wiring it in EF Core 10 Each module's `AddX` method registers its context. Inside the context: 1. `modelBuilder.HasDefaultSchema("fees")` in `OnModelCreating` puts every table of the model in the `fees` schema unless an entity says otherwise. 2. The provider options call `MigrationsHistoryTable("__EFMigrationsHistory", "fees")`. This step is easy to miss: the history table's schema comes only from this option, not from the model's default schema. Left unset, every module's context records its migrations in the same unqualified `__EFMigrationsHistory` table. 3. Migrations are added per context, for example `dotnet ef migrations add AddRefunds --context FeesDbContext`, and each module keeps its own migrations folder. A module's `DbContext` should be `internal`. Other modules then cannot inject it even if they wanted to. ## Reading another module's data The price of separate contexts is that the easy query is gone. If a Timetabling handler builds a LINQ query combining `timetablingDb.Sessions` with `admissionsDb.Students`, EF Core throws `InvalidOperationException` with the message "Cannot use multiple context instances within a single query execution". That is a feature, not a limitation to work around. The options, in order of preference: | Approach | How | Trade-off | |---|---|---| | Call the owner's contract | `IAdmissionsModule.GetEnrolledStudentsAsync(courseId)` in Admissions' public contracts, implemented inside Admissions | simple and consistent; a synchronous dependency between modules | | Keep a local read copy | Timetabling stores the student fields it needs, updated from `StudentEnrolled` events | fast local queries; eventual consistency and duplicated data | | A read-only view | Admissions publishes a database view in its schema that others may map | cheap; still couples to the database and blocks extraction | | Map the other module's tables directly | add their entities to your context | defeats the boundary; avoid | The contract call is the default. It keeps data ownership honest and turns into an HTTP call unchanged if Admissions is ever extracted. ## References between modules' entities Separate contexts also change how entities refer to each other. In a single model, an `Invoice` would have a `Student` navigation property and a foreign key constraint to the students table. Across modules, both go: - `Invoice` stores `StudentId` as a plain `Guid` column. There is no `Student` entity in `FeesDbContext` to navigate to. - No foreign key constraint crosses schemas. Admissions can archive or move its data without Fees' constraints blocking it, and Fees can later live in another database. - Fees copies the few student fields it must show on an invoice, such as the name at the time of billing, when it handles the admission event, rather than reading them live. This is the database-level version of the module contract: modules agree on identifiers and events, not on tables. ## Writes that span modules Occasionally one request must change two modules' data atomically. EF Core supports a **cross-context transaction** on a relational provider when the contexts share both a `DbConnection` and a `DbTransaction`: open the transaction on one context, then pass it to the other with `Database.UseTransactionAsync(...)`. Inside one monolith that works, but it welds the two modules to one database, so treat it as a smell. The usual alternative is to commit one module's change and let the other react to an event. ## What interviewers look for That the candidate knows the mechanics (`HasDefaultSchema`, the separate history table, `--context`), knows that a cross-context LINQ query fails at run time, and can explain why calling a contract beats sharing tables.
- Should each module's DbContext point at a separate database from day one?Usually not. Separate schemas in one database give the ownership benefits with one backup, one connection string and the option of a cross-context transaction in an emergency. Separate databases add operational cost; they make sense when a module is about to be extracted or needs a different engine. Because each context is registered inside its own module's `AddX`, moving it later is a data copy plus a connection-string change in one place.
- Two contexts map the same Student table, one read-only. Is that acceptable?Only as a deliberate, documented exception. Two models over one table means a migration in Admissions can break Timetabling at run time, and neither snapshot knows about the other. If it is accepted, the non-owning context maps a view or excludes the table from its migrations, and the table's shape becomes part of Admissions' public contract.
- HasDefaultSchema also moves the migrations history table into that schema.
- Modules should share one DbContext so cross-module joins stay easy.
- A LINQ query can join DbSets from two different DbContext instances.
- Each module's DbContext must use its own database from the start.
- Mapping another module's tables into your context is a harmless shortcut.