Setup Entity Framework For Dynamic Connection String
Nicholas Butler's answer is quite correct. In addition to what he said, I was faced with the problem of taking an existing connection string for entity framework and just pointing it at a different database that had the same structure. I used the following code to change only the data source of the existing string:
var originalConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["CSName"].ConnectionString;
var ecsBuilder = new EntityConnectionStringBuilder(originalConnectionString);
var sqlCsBuilder = new SqlConnectionStringBuilder(ecsBuilder.ProviderConnectionString)
{
DataSource = "newDBHost"
};
var providerConnectionString = sqlCsBuilder.ToString();
ecsBuilder.ProviderConnectionString = providerConnectionString;
string contextConnectionString = ecsBuilder.ToString();
using (var db = new SMSContext(contextConnectionString))
{
...
}
The generated TemplateEntities
class is marked as partial
.
All you have to do is add another file with another part of the partial class definition that exposes the constructor you want to use:
partial class TemplateEntities
{
public TemplateEntities( string nameOrConnectionString )
: base( nameOrConnectionString )
{
}
}
Then pass your connection string in to this constructor.
You want to put this code in a different file so it doesn't get over-written when you update your edmx model.