I need to connect to few databases whos look the same. I want to pass ConnectionString name as parameter when I induce instance of DB connection.
Context Class
public class AppDbContext : DbContext
{
public AppDbContext(string test) : base(GetOptions(test))
{
}
public DbSet<Cargo> Cargoes { get; set; }
private static DbContextOptions GetOptions(string connectionString)
{
return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connectionString).Options;
}
}
Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>();
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
});
}
Code
[HttpGet]
public Cargo Get()
{
var test2 = new AppDbContext("TEST");
return _appDbContext.Cargoes.FirstOrDefault(c => c.Code == "code");
}