There is only one app.config / web.config that will be read from at run time and that is the config associated with the applications entry point. So if you have a web project and a referenced project that serves at the data access layer and you want to read a connection string from the config the web.config of the web project is used. The same is true for a windows application or wpf etc, only the applications main entry point's configuration will be used. Once your application is running you can reference that app.config / web.config from anywhere in your code though as you generally do this using string identifiers.
In other words if you have a project with your Data Access compiled to MyDA.dll
and you app.config in that project that might be output to MyDA.dll.config
(this does not happen by default) anything you have in MyDA.dll.config
is ignored at runtime. The file will not be read from, only the web.config
will be used OR the app.config
of the .exe
's entry point.
For Entity Framework's DbContext
you can pass the name of the connection string directly to the constructor. You do not have to retrieve the connection string and pass it yourself. So give each connection a specific unique name in your web.config.
<connectionStrings>
<add name="ConnectionName1" connectionString="Data Source=(local);Database=YourDB;User Id=YourUser;Password=yourPassword" providerName="System.Data.SqlClient" />
<add name="ConnectionName2" connectionString="Data Source=(local);Database=YourDB2;User Id=YourUser2;Password=yourPassword2" providerName="System.Data.SqlClient" />
<!-- more here -->
</connectionStrings>
Then in your code you can create your Entity Framework's DbContext using that name.
var myEntities = new MyEntities("ConnectionName1"); // MyEntities is some class that derives from DbContext
In my past projects the DbContext
I work with usually always maps to one database at run time. What I mean here is I would not use the same DbContext type multiple times pointing to different databases. In this case I hard code that name right into my DbContext
type and make sure that my consuming applications have that connection name listed in the web.config or app.config respectively.
public class MyEntities : DbContext {
public MyEntities() : base("ConnectionName1") {}
}
// calling code now never has to know about the connection
using(var myEntities = new MyEntities()) { /* do something here */}
Alternatively if you really do want the complete connection element you can reference System.Configuration
(add it to your project references in the project where you make the following call) and call it this way.
var connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName1"];
var conString = connection.ConnectionString; // you can also get the provider
var myEntities = new MyEntities(conString);
I have not used this approach in a while but maybe there is a good reason to use it in your case.