The first approach allows you to create your own full connection string at runtime, rather than a named connection string in your app.config or web.config file.
Approach 2 uses a named connection string in your configuration files.
Using approach 1, and a partial class that handles the building of a connection string, you can build a connection string at runtime like:
The DbContext constructor accepts a connection string as a parameter.
You may be better off building a connection string and passing that to the constructor like this:
I have used something like:
// the model name in the app.config connection string (any model name - Model1?)
private static string GetConnectionString(string model, settings)
{
// Build the provider connection string with configurable settings
var providerSB = new SqlConnectionStringBuilder
{
InitialCatalog = settings.InitialCatalog,
DataSource = settings.DataSource,
UserID = settings.User,
Password = settings.Password
};
var efConnection = new EntityConnectionStringBuilder();
// or the config file based connection without provider connection string
// var efConnection = new EntityConnectionStringBuilder(@"metadata=res://*/model1.csdl|res://*/model1.ssdl|res://*/model1.msl;provider=System.Data.SqlClient;");
efConnection.Provider = "System.Data.SqlClient";
efConnection.ProviderConnectionString = providerSB.ConnectionString;
// based on whether you choose to supply the app.config connection string to the constructor
efConnection.Metadata = string.Format("res://*/Model.{0}.csdl|res://*/Model.{0}.ssdl|res://*/Model.{0}.msl", model); ;
return efConnection.ToString();
}