Creating an EDMX connection from a Regular Connection String

Posted: August 18, 2010 in ADO.NET Entity Framework

The Entity Framework is easy to slide into for Greenfield applications, isn’t everything when you got a clean slate to work with? But what about retrofitting into an existing application? One of the challenges here is the connection string itself. In a legacy system, (by legacy I mean one that does not use EF 🙂 ) We have the connection string stored in the connectionStrings section of the App or Web config file. We certainly do not want to introduce another connection string just for our EDMX, as that gives us more points of maintainability. We need to be able to build up one of those funny EDMX connection strings from an existing regular connection string. And no, string concatenation is NOT the answer here.

Here is the code: (in VB.net)

  1. Namespace Repository
  2. Public Class ConnectionFactory
  3. Public Shared Function GetEDMXConnectionString(Of T As ObjectContext)(ByVal connectionName As String) As EntityConnection
  4. Dim connectionString = ConfigurationManager.ConnectionStrings(connectionName).ConnectionString
  5. Dim dbConnection As New SqlConnection(connectionString)
  6. Dim resourceArray As String() = {“res://*/”}
  7. Dim assemblyList As Assembly() = {GetType(T).Assembly}
  8. Dim metaData As New MetadataWorkspace(resourceArray, assemblyList)
  9. Dim edmxConnection As New EntityConnection(metaData, dbConnection)
  10. Return edmxConnection
  11. End Function
  12. End Class
  13. End Namespace

There are a few things to look at here.

  1. We use a generic type of our ObjectContext. This is needed to get the assembly for the meta data.
  2. We create a stock SQL Connection
  3. We create a MetaDataWorkspace
  4. We then create an EntityConnection passing in the meta data and the SQL connection

You can then pass the resulting EntityConnection straight into your ObjectContext constructor.

Advertisements
Comments
  1. Henrique says:

    Thank you very much, you saved my life. Cheers

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s