How do you construct a DbConnection based on a provider name?
Sample provider names
- System.Data.SqlClient
- System.Data.OleDb
- System.Data.Odbc
- FirebirdSql.Data.FirebirdClient
i have connection strings stored in my IIS server's web.config file:
<connectionStrings>
<add name="development"
connectionString="Provider = IBMDA400; Data Source = MY_SYSTEM_NAME; User Id = myUsername; Password = myPassword;"
providerName="System.Data.OleDb" />
<add name="live"
connectionString="usd=sa;pwd=password;server=deathstar;"
providerName="System.Data.Odbc" />
<add name="testing"
connectionString="usd=sa;pwd=password;server=deathstar;"
providerName="System.Data.SqlClient" />
<add name="offline"
connectionString="Server=localhost;User=SYSDBA;Password=masterkey;Charser=NONE;Database=c:\data\mydb.fdb"
providerName="FirebirdSql.Data.FirebirdClient"/>
You can see they all use different providers. When it comes time for me to create a connection, i have to know what kind of DbConnection to create, e.g.:
- SqlConnection
- OleDbConnection
- OdbcConnection
- FbConnection
The connectionStrings entries contains a providerName, but these aren't the names of DbConnection descendant classes, but appear to be a namespace
How do i turn construct a DbConnection based on a string providerName?
public DbConnection GetConnection(String connectionName)
{
//Get the connectionString infomation
ConnectionStringSettings cs =
ConfigurationManager.ConnectionStrings[connectionName];
if (cs == null)
throw new ConfigurationException("Invalid connection name \""+connectionName+"\");
//Create a connection based on the provider
DbConnection conn = new DbConnection();
}
If the providerName for the particular connection name (dev, test, prod) never changes why cant you do a switch on the connectionName param for your method and set the providerName instance that way?
Check out this Hanselman blog on adding custom build types for different connection strings names, it looks like it may fit what you want to accomplish in a different way than using the provider types.
If you go this route, I think you'll want to use the DbProviderFactories class to get a DbProviderFactory that you can use to construct the connection. I haven't tried this code out, but I think it will work. It's possible that you may need to look up the provider name using the GetFactoryClasses method on the DbProviderFactories class and use the InvariantName.