You can set connection string used by EF Core context in runtime:
Code: Select all
var optionsBuilder = new DbContextOptionsBuilder<ModelContext>();
optionsBuilder.UseMySql(@"User Id=root;Password=root;Host=db;Port=3311;Database=aaaa;");
var context = new ModelContext(optionsBuilder.Options);
var result = context.Depts.ToList();
var optionsBuilder2 = new DbContextOptionsBuilder<ModelContext>();
optionsBuilder2.UseMySql(@"User Id=root;Password=root;Host=db;Port=3312;Database=bbbb;");
var context2 = new ModelContext(optionsBuilder2.Options);
var result2 = context2.Depts.ToList();
There is a known issue: our EF Core template currently generates the following code
Code: Select all
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(@"...");
CustomizeConfiguration(ref optionsBuilder);
base.OnConfiguring(optionsBuilder);
}
which overrides connection string set via your own code. We will fix code generation in this way
Code: Select all
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.Options.Extensions.OfType<RelationalOptionsExtension>().Any(ext => !string.IsNullOrEmpty(ext.ConnectionString) || ext.Connection != null))
optionsBuilder.UseMySql(@"...");
CustomizeConfiguration(ref optionsBuilder);
base.OnConfiguring(optionsBuilder);
}
and will notify you when the change is included in a predefined EF Core template.