Listen to this Post
When working with complex applications, especially modular monoliths, using multiple Entity Framework (EF) Core DbContexts can be a game-changer. This approach is particularly useful when dealing with multiple databases, separating concerns, or implementing read replicas. Here’s a breakdown of how to effectively use multiple DbContexts in a single application.
When to Use Multiple DbContexts:
- Working with Multiple Databases: If your application interacts with more than one database, separate DbContexts can help manage these interactions efficiently.
- Separating Concerns: Different modules or components of your application might have distinct data access requirements. Using separate DbContexts can help keep these concerns isolated.
- Modular Monoliths: In a modular monolith architecture, each module can have its own DbContext, which simplifies database schema management and migrations.
- Read Replicas: If your application uses read replicas for scaling read operations, separate DbContexts can help manage these connections.
How EF Core Handles Migrations and Schemas:
EF Core allows you to create separate migrations for different DbContexts, even when they interact with the same database but different schemas. This is particularly useful in modular monoliths where each module has its own schema.
Practical Example:
Here’s how you can set up multiple DbContexts in an ASP.NET Core application:
// DbContext for Module A
public class ModuleADbContext : DbContext
{
public ModuleADbContext(DbContextOptions<ModuleADbContext> options) : base(options) { }
public DbSet<ModuleAEntity> ModuleAEntities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("ModuleA");
}
}
// DbContext for Module B
public class ModuleBDbContext : DbContext
{
public ModuleBDbContext(DbContextOptions<ModuleBDbContext> options) : base(options) { }
public DbSet<ModuleBEntity> ModuleBEntities { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("ModuleB");
}
}
Configuring DbContexts in Startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ModuleADbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ModuleAConnection")));
services.AddDbContext<ModuleBDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("ModuleBConnection")));
// Other service configurations
}
Handling Migrations:
To create and apply migrations for each DbContext, use the following commands:
<h1>For ModuleA</h1> dotnet ef migrations add InitialCreate --context ModuleADbContext dotnet ef database update --context ModuleADbContext <h1>For ModuleB</h1> dotnet ef migrations add InitialCreate --context ModuleBDbContext dotnet ef database update --context ModuleBDbContext
You Should Know:
- Schema Management: EF Core allows you to specify different schemas for each DbContext, which is useful in modular applications.
- Migrations: Separate migrations can be created for each DbContext, even if they are targeting the same database.
- Dependency Injection: Ensure that each DbContext is correctly registered in the DI container to avoid conflicts.
What Undercode Say:
Using multiple DbContexts in a single application can significantly improve the modularity and scalability of your application. It allows for better separation of concerns and simplifies database schema management. However, it’s crucial to handle migrations and dependency injection carefully to avoid potential issues. For more advanced scenarios, consider exploring tools like Fluent Migrator for handling migrations across multiple databases.
Related Commands:
- Linux: `psql -U username -d dbname` (Connect to PostgreSQL database)
- Windows: `sqlcmd -S servername -U username -P password` (Connect to SQL Server)
- EF Core: `dotnet ef migrations add
` (Create a new migration) - EF Core: `dotnet ef database update` (Apply migrations to the database)
For more detailed guidance, refer to the official EF Core documentation: EF Core Documentation
References:
Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅



