Getting the provider connection string from an entity connection string (or an entity model instance)

Posted: (EET/GMT+2)

 

I recently needed a fast way to import hundreds of thousands of rows into a SQL Server database, and as I've blogged before, the Entity Framework I'm normally using for my database access, isn't performing well enough in these kind of mass (bulk) insert situations.

However, the majority of the database access logic in this application is indeed using Entity Framework (EF), so I didn't want to change this just because a single routine (the bulk import) needs more performance. Similarly, I didn't want to specify multiple connection strings in the web.config file (it's an ASP.NET web application), so I thought I'd use the existing connection string for EF.

To get the ADO.NET connection string (the "provider connection string") out of the pretty long EF connection string, you can use the EntityConnectionStringBuilder class. In addition, you can create an EF entity object, and then ask for the connection's ConnectionString property.

Here's a C# example on how to implement this in these two ways:

// method 1, get the provider connection string from web.config
using System.Configuration;
using System.Data.Entity.Core.EntityClient;
...
ConnectionStringSettings setting = ConfigurationManager.ConnectionStrings["MyEntities"];
string entityConnectionString = setting.ConnectionString;
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder(entityConnectionString);
string providerConnectionString = builder.ProviderConnectionString;

// method 2, get the provider connection string from an entity object
MyEntities entities = new MyEntities();
string providerConnectionString2 = entities.Database.Connection.ConnectionString;

Hope this helps!