Provider connection string from Entity Framework
Asked Answered
P

2

20

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.

Pistoleer answered 7/8, 2012 at 7:7 Comment(0)
P
42

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;
Pistoleer answered 7/8, 2012 at 7:7 Comment(0)
P
0

I have to confess I cheated because I didn't want the dependency on EF's assembly in the project I was working on. So I used a regex to "parse" the 'provider connection string' value thusly:

provider connection string="(.+)";
Percheron answered 8/4, 2021 at 0:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.