So you can target a connection string with a DbContext, but you need to make sure that your class implementation has a constructor that accepts a string parameter and passes it to the base constructor. You will also need to access the connection strings manually. Your derived DbContext will need to look something like this:
public class MyDbContext : DbContext
{
...
public MyDbContext(string connStr) : base(connStr)
{
}
}
Now you can spin off a little factory class that will return a copy of your DbContext with the appropriate connection target. There's no resilience in this sample, and if you want to have a default return context you can replace the exception with a default return.
public class DbSelector
{
public static MyDbContext GetContext(string name)
{
var connStrConfig = ConfigurationManager.ConnectionStrings[name];
if(connStrConfig != null
&& !string.IsNullOrWhitespace(connStrConfig.ConnectionString))
{
return new MyDbContext(connStrConfig.ConnectionString);
}else{
throw new Exception("Invalid Configuration String requested.");
}
}
}
From there, getting a targeted MyDbContext is simple.
DbSelector.GetContext("dbContext_1");