First I created the DbContext and I have added 2 DbSets
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Department> Departments { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
The Models I've been created
Employee
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
}
Department
public class Department
{
public int Id { get; set; }
public string DepartmentName { get; set; }
public virtual List<Employee> Employees { get; set; } = new();
}
Go to the controller and create an endpoint that will take connection string name that is needed to switch as a parameter then it will go and check if it exists then it will be changed from the controller
[Route("api/[controller]")]
[ApiController]
public class DbController : ControllerBase
{
private readonly IConfiguration configuration;
private readonly IServiceProvider serviceProvider;
private readonly IConnectionString connectionString;
public DbController(IConfiguration configuration, IServiceProvider serviceProvider,IConnectionString connectionString)
{
this.configuration = configuration;
this.serviceProvider = serviceProvider;
this.connectionString = connectionString;
}
[HttpGet("change-db")]
public IActionResult ChangeDB(string connectionStringName)
{
string? conString = configuration.GetConnectionString(connectionStringName);
// Validate the connection string
if (string.IsNullOrEmpty(conString))
return BadRequest("Can't find this database");
var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
optionsBuilder.UseSqlServer(conString);
var dbContext = new AppDbContext(optionsBuilder.Options);
connectionString.CurrentConnectionString = dbContext is not null ? connectionStringName : string.Empty;
var initialCatalog = conString.Split(';')
.FirstOrDefault(part => part.StartsWith("Initial Catalog", StringComparison.OrdinalIgnoreCase))?
.Split('=')[1].Trim();
return Ok($"Switched to {initialCatalog} database.");
}
This will return "Switched to {Database name} database." if it exists else it will return a Bad request
The IConnectionString is only used to save my connection string name to be used in another controllers
The interface
public interface IConnectionString
{
string CurrentConnectionString { get; set; }
}
The Class
public class ConnectionString : IConnectionString
{
public string CurrentConnectionString { get; set; } = string.Empty;
}
It must be injected at the Program.cs
builder.Services.AddSingleton<IConnectionString, ConnectionString>();
The Connection string must be the default here and it will be changed after calling the endpoint
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
options.UseSqlServersuffice? e.g.if(Environment.GetEnvironmentVariable("FIRSTENVIRONMENT") options.UseSqlServer("firstEnvironementConnectionString") else options.UseSqlServer("secondEnvironementConnectionString")if(Environment.GetEnvironmentVariable("FIRSTENVIRONMENT") == "environmentString") options.UseSqlServer("firstEnvironementConnectionString") else options.UseSqlServer("secondEnvironementConnectionString")