Using an entity framework connection string in ADO

ado.net, c#, connection-string, entity-framework

Solution

You can get `DbConnection` instance from `DbContext`:

var context = new YourDbContext();
var connection = context.Database.Connection;

Of course, you can get connection string from connection, but you don't need thus you can use already existing connection object.

Here is Quick Watch of `connection` object - as you can see it's simple ADO.NET SqlConnection object with ordinal connection string.

In config file I have Entity Framework connection string with metadata:

  <connectionStrings>
    <add name="NorthwindEntities"
         connectionString="metadata=res://*/Northwind.csdl|res://*/Northwind.ssdl|res://*/Northwind.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.;initial catalog=Northwind;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
         providerName="System.Data.EntityClient" />
  </connectionStrings>

Problem

We have a need to use an old fashioned ADO database connection in one tiny part of the main entity framework application. We can manually specify the connection string in this part of code, but given that the connection string is already present in the App.Config this seems redundant. However when we use the configuration manager to retrieve the connection string, it brings with it all of the metadata stuff that entity framework uses. This causes an error as ADO doesnt recognise the metadata keyword. How can I parse this connection string to remove the metadata and just get the plain ADO connection string?

Original source