Following the spirit of Primer to ConnectionStringBuilder from ADO.NET 2.0, let’s see how the pattern has evolved in Entity Framework.
Building an Entity Connection String from Scratch
What’s important to keep in mind before we dive into code samples, is that an entity connection string consists of two separate connection strings – one for the EntityClient itself and one for the underlying store provider. Therefore we’ll be using two connection string builders to build a full entity connection string.
We need to start with the part specific to EntityClient:
Then we dynamically construct a DbConnectionStringBuilder for the given provider (using DbProviderFactory), and we allow the user to enter values for its keywords:
What’s left is to set the provider-specific connection string on the EntityConnectionStringBuilder:
To get the connection string out of the connection string builder, you need to call the ToString() method:
The ReadKeyValue utility method that reads a line of text from the console. (Attached is the complete source code.)
Loading an Entity Connection String
EntityConnectionStringBuilder implements the concept of “named” connections. This has been a long time ask. Connection strings are built through VisualStudio wizard, or third-party tools, or by hand, and placed into the app.config/web.config file:
Then the application no longer needs to worry about “building” the connection string. It only needs to “load”. Like this:
Look up the attached source code for details.