Reputation: 50
How do I switch the database that my entity model is connected to at runtime?
If I have a training database and a production database, for example, how can I make my application switch between the two by changing a setting in the application.
Upvotes: 0
Views: 521
Reputation: 2216
Justin Pihony has the correct answer. If you want to access both databases at the same time (switch back and forth) instead of changing config and restarting app.....then you have two settings one for Train and one for Prod then you do your context like so:
string training = ConfigurationManager.ConnectionStrings["Train"].ToString();
string production = ConfigurationManager.ConnectionStrings["Prod"].ToString();
.....
EFContext context = null;
if (InTraining)
context = new EfContext(training);
else
context = new EfContext(production);
Upvotes: 1
Reputation: 67135
Usually this is done by a config file setting. Here is the MSDN on EF connection strings and here is some more info on it, basically saying it should be in your app.config
And, if you want something from the code, here is a code project:
string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;
dataContext = new SampleEntities(ecb.ConnectionString);
Upvotes: 1