问题
If you are using object contex data model (with EDMX file), during its creation you might want to specify the connection string inside your config file.
The connection string is unfortunately not the common connection string as it contains some ...things needed for the entity connections. Example with MySql connection:
<add name="MyDbEntities" connectionString="metadata=res://*/Namespace.MyDb.csdl|res://*/Namespace.MyDb.ssdl|res://*/Namespace.MyDb.msl;provider=MySql.Data.MySqlClient;provider connection string="server=172.17.17.154;User Id=user;password=password;Persist Security Info=True;database=MyDatabase;Convert Zero Datetime=true"" providerName="System.Data.EntityClient" />
The problem I have is that this connection string contains the connection string of the provider in the parameter "provider connection string".
For a specific reason, I need to create a new MySqlConnection, unrelated to the entity model. For creating the MySqlConnection, I need to provide it the mysql connection string - which is the provider connection string for the entity model and I know the connection string I need is always the same connection string for the entity model.
But how do I get the provider connection string programmaticaly? I was stuck with browsing the model instance with no success...
The following:
ModelInstance.Connection.ConnectionString
contains something like "name=TestBotEntities", not even the whole connection string. So I tried:
ConfigurationManager.ConnectionStrings["MyDbEntities"].ConnectionString
but that one contains the whole entity connection string and I just don't know how to parse it, how to get only the provider connection string from it.
回答1:
Turns out there are two ways.
I could parse the entity connection string via the EntityConnectionStringBuilder:
string entityConnectionString = ConfigurationManager.ConnectionStrings["MyDbEntities"].ConnectionString;
string providerConnectionString = new EntityConnectionStringBuilder(entityConnectionString).ProviderConnectionString;
...or if I have the specific model instance available, I can get it from here.
((System.Data.EntityClient.EntityConnection)ModelInstance.Connection).StoreConnection.ConnectionString;
来源:https://stackoverflow.com/questions/11840896/provider-connection-string-from-entity-framework