I have 2 connection strings in my appsettings.json and I use dbContext.Database.Migrate(); in Configure method to create the database if the primary connection string that I used to create the DbContext service in ConfigureServices method was incorrect, I face Exception so I want to change the connection string of the Dbcontext service in the exception area. How can I achieve that?
I tried to do the migration in ConfigureServices but I don't know how to create a DbContext object and how to test it.
in ConfigureServices
services.AddDbContext<RedContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
in Configure
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetService<RedContext>();
var roleManager = serviceScope.ServiceProvider.GetService<RoleManager<IdentityRole>>();
var userManager = serviceScope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
// Create the Db if it doesn't exist and applies any pending migration.
try
{
dbContext.Database.Migrate();// throws exception if CS is wrong
DbSeeder.Seed(dbContext, roleManager, userManager);
}
catch (Exception)
{
// remove old service and create new dbcontext DI service in IserviceCollection with secondary connection string
//dbContext.Database.Migrate();
// dbContext.Database.GetDbConnection()
}