Extract connection string from an Entity Connection String
Assuming you have an instance of the ObjectContext
(if you are using the built-in designer, your context derives from the EF ObjectContext
class). You can cast the value of the ObjectContext.Connection
property (which is a DbConnection) to an EntityConnection
.
The EntityConnection
class has a property StoreConnection
which is the actual DbConnection
used to connect to the database. This one actually has the ConnectionString
property set to the one you are looking for.
Edit: Some sample code (Assign context to your ObjectContext):
ObjectContext context = entities;
EntityConnection entityConnection = context.Connection as EntityConnection;
if (null != entityConnection)
{
Console.WriteLine(entityConnection.StoreConnection.ConnectionString);
}
While Jan Remunda rightly points out that you don't need to create a context, and while his solution is useful if you want to create a connection explicitly right after reading the EntityClient
connection string, it's still a little convoluted if all you want is to retrieve the inner-provider connection string (which is what OP asks).
It's true that you don't have to open the connection, you can just retrieve the ConnectionString
of the inner StoreConnection
then discard it right after, but why?
Use the appropriate connection string builder instead:
new EntityConnectionStringBuilder(outerConnectionString).ProviderConnectionString
See EntityConnectionStringBuilder.