I had this problem with a project... everything is fine, all wonders... When you run the application in you computer, how do you adapt the database connection to the different users?
I did everything here and other many post similar to this, and nothing seams to work... Yes, the code works, the data context catch the new info for the connection, but it simply DON'T WORK... :'(
I found a lifesaver example that solve my problems, it's a bunch of code but, DBCon
has the information of the new connection:
Encripter enc = new Encripter();
string strconfig = u.readFile(u.ubicacionActual() + "\\conn.config");
DBCon dbcon = JsonConvert.DeserializeObject<DBCon>(enc.decrypt(strconfig));
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
EntityConnectionStringBuilder efb = new EntityConnectionStringBuilder(config.ConnectionStrings.ConnectionStrings["ProyectEntities"].ConnectionString);
SqlConnectionStringBuilder sqb = new SqlConnectionStringBuilder(efb.ProviderConnectionString);
// Now we can set the datasource
sqb.DataSource = dbcon.datasource;
sqb.InitialCatalog = dbcon.catalog;
sqb.UserID = dbcon.user;
sqb.Password = dbcon.password;
efb.ProviderConnectionString = sqb.ConnectionString;
// to rewrite the app.config!
ChangeEFConnectionString("ProyectEntities", efb.ProviderConnectionString);
ProyectEntities db = new ProyectEntities(); // dbcontext
The magic function (Well it's not really magic! Just overwrite the app.config
)
private bool ChangeEFConnectionString(string connStringName, string newValue)
{
try
{
//CreateXDocument and load configuration file
XDocument doc = XDocument.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
//Find all connection strings
var query1 = from p in doc.Descendants("connectionStrings").Descendants()
select p;
//Go through each connection string elements find atribute specified by argument and replace its value with newVAlue
foreach (var child in query1)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == connStringName)
{
if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
{
// Create the EF connection string from existing
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(atr.NextAttribute.Value);
//
entityBuilder.ProviderConnectionString = newValue;
//back the modified connection string to the configuration file
atr.NextAttribute.Value = entityBuilder.ToString();
}
}
}
}
doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
All credits to a Bahrudin Hrnjica