質問

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?

役に立ちましたか?

解決

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>

他のヒント

Below should work :

var efConn = new System.Data.EntityClient.EntityConnectionStringBuilder(efConnection);                     
string adoConn =  efConn.ProviderConnectionString;

I was trying to the same and ended up using this approach:

private static string RemoveEntityFrameworkMetadata(string efConnection)
{
  int start = efConnection.IndexOf("\"", StringComparison.OrdinalIgnoreCase);
  int end   = efConnection.LastIndexOf("\"", StringComparison.OrdinalIgnoreCase);

  // We do not want to include the quotation marks
  start++;
  int length = end - start;

  string pureSqlConnection = entityFrameworkConnection.Substring(start, length);
  return pureSqlConnection;
}

This may not be the most elegant solution, but it works.

(I also tried Regex but can't get my head around it.)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top