How to Obtain the Provider Connection String From an Entity Connection String

This technique might come in useful if you find yourself in a situation where you want to be able to execute untyped queries against the DB but don’t want to have to maintain two connection strings.

Parse the Provider Name and Connection String

Put this code into your partial ObjectContext class:

EntityConnectionStringBuilder _builder;
private EntityConnectionStringBuilder EntityConnStrBuilder
{
get
{
if (_builder == null)
{
_builder = new EntityConnectionStringBuilder(Connection.ConnectionString);
if (!String.IsNullOrWhiteSpace(_builder.Name))
_builder = new EntityConnectionStringBuilder(
ConfigurationManager.ConnectionStrings[_builder.Name].ConnectionString);
}
return _builder;
}
}

public string ProviderName
{
get { return EntityConnStrBuilder.Provider; }
}

public string ProviderConnectionString
{
get { return EntityConnStrBuilder.ProviderConnectionString; }
}
In a nutshell, this code uses ConnectionStringBuilders to parse the connection string(s). You can expose the properties of the EntityConnectionStringBuilder however you prefer, but the ones above are the ones that you’ll need next.

Execute Non-Entity Queries With DbProviderFactory

Once you have the provider name and connection string, you can use the DbProviderFactory class to create provider-specific connections and commands.

using (var context = new ExampleEntities())
{
var factory = DbProviderFactories.GetFactory(context.ProviderName);
using (var connection = factory.CreateConnection())
{
connection.ConnectionString = context.ProviderConnectionString;
// Open connection, use factory to create commands, adapters, etc.
This technique works ideally with the lightweight Dapper ORM to add high-performance read-only or multi-result querying to a project that is already using EF as the primary means of data access.
comments powered by Disqus