我有一个连接字符串传递给一个函数,我需要基于这个字符串创建一个基于DbConnection的对象(即SQLConnection,OracleConnection,OLEDbConnection等)。
是否有任何内置的功能,或任何第三方图书馆协助。我们不一定构建这个连接字符串,所以我们不能依赖字符串写入的格式来确定它的类型,我宁可不必对可能的连接字符串的所有组合和排列进行编码
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()
.FirstOrDefault(x=>x.ConnectionString==connStr);
if (css != null) providerName = css.ProviderName;
}
if (providerName != null)
{ var providerExists = DbProviderFactories
.GetFactoryClasses()
.Rows.Cast()
.Any(r=>r[2].Equals(providerName));
if (providerExists)
{ var factory = DbProviderFactories.GetFactory(providerName);
var dbConnection = factory.CreateConnection();
dbConnection.ConnectionString = connStr;
return dbConnection;
}
}
return null;
}