How to access DAAB connection strings placed in separate configuration file at runtime?

Topics: Data Access Application Block, Enterprise Library Core
Nov 7, 2009 at 8:18 AM
Edited Nov 7, 2009 at 10:36 AM

Hello everyone!

I am on my early stages of learning ASP.NET MVC and I came across an issue that proved somehow difficult for me to solve.

The Data Access layer is built using Linq to Sql classes and the database is represented by an instance of SQL Server 2005 (not SQLEXPRESS, jut to be clear!). I have chosen to put the DAAB in its separate config file and I have created the necessary connection string for my SQL Server instance.  "SelectedSource" property for Configuration Sources block is set to System Configuration Source. Version of Enterprise Library is 4.1.

Now I want to initialize the database connection at run time using the DefaultDatabase connection string.



I need the DefaultDatabase connection string to initialize my DataContext descendent that was created by the LINQ to SQL editor.

I have used several approaches but they all have failed. EntLib 4.1 docs are not very descriptive about this particular task of mine, although I suspect the task to be not so uncommon. At the current moment I am stuck with the following code:

public string DefaultConnectionString
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = "dataconfiguration.config";
        Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        ConnectionStringsSection connStringsSection = config.ConnectionStrings;
        ConnectionStringSettings connStringsSettings = connStringsSection.ConnectionStrings["DefaultDatabase"];
        return connStringsSettings.ConnectionString;
This property returns the empty string so obviously I am not reaching to my own connection string. The variable connStringsSettings only contains the default LocalSqlServer connection string. (Side note: Why is EntLib editor so stubborn about placing DAAB in both App.config and DataConfiguration.config when I clearly delete the block from App.config??)
Has anyone had a similar task that solved succesfully?
Thank you!
Nov 9, 2009 at 2:24 AM

You can use the configSource attribute in your config.  In your app.config, you'll have this:

 <connectionStrings configSource="dataConfiguration.config"/>

In your code, you can create access the connection strings by calling:

<font size="2">



IConfigurationSource entLibConfig = ConfigurationSourceFactory.Create();

ConnectionStringsSection connStringsSection = (ConnectionStringsSection)entLibConfig.GetSection("connectionStrings");


Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.

<font size="2" color="#0000ff"><font size="2" color="#0000ff">


</font></font><font size="2" color="#0000ff">