C# connection strings contains Provider Name. By Default it's missing that's mean provider is System.Data.SqlClient. For other providers provide name must be provided.
When nameOrConnectionString is a connection string - what providerName should be used?
-
12-10-2022 - |
Question
I am writing my own class that wraps some ADO.NET calls, one of the parameters I want to accept is a "nameOrConnectionString" similar to what lots of ORMs seem to accept
If the parameter is a name (I can determine this by the number of '=' characters in the string) then I can go to the config file and get the actual connectionString as well as the providerName - there is no issue.
But if I was passed a connectionString, how do I determine the which providerName to use, is there a parameter within the connectionString that can specify this, should it default to something reasonable like System.Data.SqlClient
, or is there no real standard around this?
Some code to illustrate
public Db(string nameOrConnectionString)
{
string connectionString;
string providerName;
string name;
//some method that determines if the nameOrConnectionString is a name and outputs the name
if(ParseConnectionStringName(out name)){
//if its a name i can pull relevant details from config
var settings = ConfigurationManager.ConnectionStrings[name];
if (settings == null)
throw new ArgumentException("nameOrConnectionString");
connectionString = settings.ConnectionString;
providerName = settings.ProviderName;
}
else
{
//nameOrConnectionString is a connectionString, but what is providerName
connectionString = nameOrConnectionString;
providerName = "????" //what should this be?
}
//I need provider name to get a DbProviderFactory
DbProviderFactory = DbProviderFactories.GetFactory(providerName);
//....
}
Solution
OTHER TIPS
An OLE DB connection string will always have a provider value and an ODBC connection string will always have a driver. Mind you, if you use a DSN with ODBC then the driver will be in the DSN. There's really is no way to know to know for sure in all cases though. I haven't used lots of ORMs but Entity Framework stores the provider in the config file too. I'd not be surprised if others did too.
You can have a look at this how to add provider name to connection string http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.sqldatasource.providername(v=vs.110).aspx
connection string has this format you can split the string to get provider name from nameOrConnectionString
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Server=215- 6576;User ID=sa; Database=All-PurposeHandyman; Password=password"
providerName="System.Data.SqlClient" />