Search code examples
.netado.netconnection-stringdbconnection

C# Retrieving correct DbConnection object by connection string


I have a connection string being passed to a function, and I need to create a DbConnection based object (i.e. SQLConnection, OracleConnection, OLEDbConnection etc) based on this string.

Is there any inbuilt functionality to do this, or any 3rd party libraries to assist. We are not necessarily building this connection string, so we cannot rely on a format the string is written in to determine its type, and I would prefer not to have to code up all combinations and permutations of possible connection strings


Solution

  • DbConnection GetConnection(string connStr)
    {
        string providerName = null;
        var    csb = new DbConnectionStringBuilder { ConnectionString = connStr };
                                                            
        if (csb.ContainsKey("provider")) 
        {
            providerName = csb["provider"].ToString();
        }          
        else
        {
            var css = ConfigurationManager
                .ConnectionStrings
                .Cast<ConnectionStringSettings>()
                .FirstOrDefault(x => x.ConnectionString == connStr);
            if (css != null) providerName = css.ProviderName;
        }
               
        if (providerName != null) 
        {
            var providerExists = DbProviderFactories
                .GetFactoryClasses()
                .Rows.Cast<DataRow>()
                .Any(r => r[2].Equals(providerName));
            if (providerExists) 
            {
                var factory = DbProviderFactories.GetFactory(providerName);
                var dbConnection = factory.CreateConnection();
                    
                dbConnection.ConnectionString = connStr;
                return dbConnection;
            }
        }
               
        return null;
    }