Introduction
Entity Framework Core (EF Core) is a powerful ORM tool for working with databases in .NET applications. In some scenarios, you may need to work with multiple databases or database contexts within a single application. This could arise from the need to interact with different database schemas, manage separate databases for different modules, or integrate with external systems. In this blog post, we'll explore how to effectively manage multiple EF Core DbContexts in a single .NET application.
Define Multiple DbContext Classes
Start by defining separate DbContext classes for each database or database schema you need to work with.
Each DbContext class represents a distinct database context and should inherit from DbContext.
public class AppDbContext : DbContext
{
// DbSet properties and configurations
}
public class AnotherDbContext : DbContext
{
// DbSet properties and configurations
}
Register DbContexts with Dependency Injection
In ASP.NET Core applications, register DbContext classes with the built-in dependency injection container.
Use the AddDbContext method to register each DbContext, specifying the connection string and options.
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppConnection")));
services.AddDbContext<AnotherDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AnotherConnection")));
Accessing DbContext Instances
Inject the DbContext instances into your services or controllers where needed.
Use constructor injection to access the DbContext instances.
public class MyService
{
private readonly AppDbContext _dbContext;
public MyService(AppDbContext dbContext)
{
_dbContext = dbContext;
}
// Use _dbContext for database operations
}
Managing Transactions Across DbContexts
When performing transactions involving multiple DbContexts, ensure proper coordination to maintain data integrity.
Use distributed transactions or implement a custom unit of work pattern if needed.
using (var transaction = _dbContext.Database.BeginTransaction())
{
// Perform operations on _dbContext and AnotherDbContext
transaction.Commit();
}
Testing and Maintenance
Write integration tests to ensure that interactions between multiple DbContexts work as expected.
Regularly review and update DbContext configurations, including database connection strings and entity mappings.
Below is an example of an end-to-end order processing application using multiple EF Core DbContexts in a .NET application:
Define DbContext Classes
// AppDbContext.cs
public class AppDbContext : DbContext
{
public DbSet<Order> Orders { get; set; }
// Other DbSet properties and configurations
}
// CustomerDbContext.cs
public class CustomerDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
// Other DbSet properties and configurations
}

Join the conversation! Your thoughts help the community grow.