views:

77

answers:

2

Hi all,

Is it possible to change a database connection string value in the Web.Config at runtime without reloading the application domain? The reason for doing this is that:

  1. I am building a multi-tenanted application which uses the one code instance and multiple databases instances approach, so the database connection string in the web.config must be able to be changed at runtime for different tenant users.

  2. ADO.NET always injecst the database connection string in the web.config when you are using entity framework/LINQ to SQL etc, dataset etc.

So I may have to do something weird like this. Hope it is clear enough. Thanks a lot!

+5  A: 

Yes it is possible. try this

System.Configuration.Configuration conf = WebConfigurationManager.OpenWebConfiguration(Server.MapPath);
conf.ConnectionStrings.ConnectionStrings["comp1"].ConnectionString = _connection_comp1;
conf.ConnectionStrings.ConnectionStrings["comp2"].ConnectionString = _connection_comp2;
conf.AppSettings.Settings["CompanyCode"].Value = _company_code;
conf.Save();
RJ1516
hi, guys, thank you for the answer. I have not got the chance to try it :) But I have thought of a way to get around of updating the value in the web.config since it is not flexible. I am putting my tenant company database connection string to the session, which is a much reasonable place to get/set the connection string.
schrodinger's code