0
The question is exactly as in the title of this topic, but all the help I found related to the subject is running the code on the application startup requiring arguments to be passed to the host.
I would like to run the Migrations in a method of my controller after the user login in the system because I have a Multi Tenant scheme where I work with several banks and direct the user to your bank after the login changing the Connection String in memory.
References:
https://stackoverflow.com/questions/41090881/migrating-at-runtime-with-entity-framework-core https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/applying?tabs=dotnet-core-cli
Code found to place on startup:
public void ConfigureServices(IServiceCollection services)
{
// Wire up whatever your equivalent DbContext class is here
services.AddDbContext<ApplicationDbContext>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
}
}
My Login Method:
public IActionResult Login(LoginViewModel loginVm)
{
Constants.ConnectionString = config.GetConnectionString("ConnString_Generica").Replace("[CLIENTE]", loginVm.Cnpj);
try
{
using (var connection = new SqlConnection(Constants.ConnectionString))
{
connection.Open();
}
}
catch (Exception)
{
loginVm.MessageValidation = Resources.Resources.TentativaInvalida;
return View(loginVm);
}
///Após isso aplicar os migrations
}
You can’t instantiate the
DbMigrator
and run the update method? Or even direct byApplicationDbContext
?– Leandro Angelo