Working with two or more DbContexts in Entity Framework Core is beneficial when an element of an application has different databases or when different models are used in an application. This is especially advantageous in multi modular systems where each module or a particular feature has different database needs.
Here is a basic procedure on how to use this strategy effectively:
1. Define Your DbContexts
In this approach, different types of DbContexts shall be created in different classes.
public class AppDbContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Order> Orders { get; set; }
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
}
public class AuditDbContext : DbContext
{
public DbSet<AuditLog> AuditLogs { get; set; }
public AuditDbContext(DbContextOptions<AuditDbContext> options)
: base(options) { }
}
2. Configure in Startup.cs or Program.cs file
In the AddDbContext method connect each DbContext to its own particular connection string.
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AppConnection")));
services.AddDbContext<AuditDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("AuditConnection")));
3. Use Multiple Contexts in Services
Inject required DbContext into services.
public class UserService
{
private readonly AppDbContext _appDbContext;
private readonly AuditDbContext _auditDbContext;
public UserService(AppDbContext appDbContext, AuditDbContext auditDbContext)
{
_appDbContext = appDbContext;
_auditDbContext = auditDbContext;
}
public async Task CreateUser(User user)
{
_appDbContext.Users.Add(user);
await _appDbContext.SaveChangesAsync();
var auditLog = new AuditLog
{
Action = "CreateUser",
Timestamp = DateTime.UtcNow
};
_auditDbContext.AuditLogs.Add(auditLog);
await _auditDbContext.SaveChangesAsync();
}
}
Ready to transform your business with our technology solutions? Contact Us today to Leverage Our .Net Expertise.
0