Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an entity framework connection string in ADO

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?

like image 536
Steven Wood Avatar asked Dec 14 '22 22:12

Steven Wood


2 Answers

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.

enter image description here

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>
like image 135
Sergey Berezovskiy Avatar answered Jan 07 '23 13:01

Sergey Berezovskiy


Below should work :

var efConn = new System.Data.EntityClient.EntityConnectionStringBuilder(efConnection);                     
string adoConn =  efConn.ProviderConnectionString;
like image 32
Miguel Perez Avatar answered Jan 07 '23 14:01

Miguel Perez