Provider connection string from Entity Framework

◇◆丶佛笑我妖孽 提交于 2019-11-27 02:42:27

问题


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=&quot;server=172.17.17.154;User Id=user;password=password;Persist Security Info=True;database=MyDatabase;Convert Zero Datetime=true&quot;" 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!