Dynamically Generating Connection String for Entity Framework

Sometimes, there comes a scenario where you are using certain architecture for your work but due to some issue or for some enhancement in the system you need to use two different connection providers, one for a simple connection and other for entity framework.

In my case I am using LINQ to SQL and entity framework altogether for doing some work.

What is the need for creating connection string dynamically for entity framework?

The real need arises as .edmx entity framework data objects create different connection strings than the linq to sql or we simply use in web.config file that's why we need to generate dynamically by using built in classes in C#.

Simple Connection string:
  1. <add name="ConnectionString9" connectionString="server=ServerName;database=DatabaseName;uid=db_user_id;password=db_user_password; Connect Timeout=0; Max Pool Size=5000"/> 
Entity Connection String:
  1. <add name="DBEntities" connectionString="metadata=res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;provider=System.Data.SqlClient;provider connection string="data sourceServerName;initial catalog=DB_Name;persist security info=True;user id=DBUserID;password=DBUserPassword;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
So let's start it to build the connection string dynamically to be used in project. Firstly, we add required namespaces to be used in method.
  1. using System.Configuration;  
  2. using System.Data.SqlClient;  
  3. using System.Data.Entity.Core.EntityClient;  
Secondly, we Create Class and include the method for creating connection string dynamically.
  1. public string GenerateConnectionStringEntity(string connEntity)  
  2. {  
  3.   // Initialize the SqlConnectionStringBuilder.  
  4.     string dbServer = string.Empty;  
  5.     string dbName = string.Empty;  
  6.     // use it from previously built normal connection string  
  7.     string connectString = Convert.ToString(ConfigurationManager.ConnectionStrings[connEntity]);  
  8.     var sqlBuilder = new SqlConnectionStringBuilder(connectString);  
  9.     // Set the properties for the data source.  
  10.     dbServer = sqlBuilder.DataSource;  
  11.     dbName = sqlBuilder.InitialCatalog;  
  12.     sqlBuilder.UserID = "Database_User_ID";  
  13.     sqlBuilder.Password = "Database_User_Password";  
  14.     sqlBuilder.IntegratedSecurity = false;  
  15.     sqlBuilder.MultipleActiveResultSets = true;  
  16.     // Build the SqlConnection connection string.  
  17.     string providerString = Convert.ToString(sqlBuilder);  
  18.     // Initialize the EntityConnectionStringBuilder.  
  19.     var entityBuilder = new EntityConnectionStringBuilder();  
  20.     //Set the provider name.  
  21.     entityBuilder.Provider = "System.Data.SqlClient";  
  22.     // Set the provider-specific connection string.  
  23.     entityBuilder.ProviderConnectionString = providerString;  
  24.     // Set the Metadata location.  
  25.     entityBuilder.Metadata = @ "res://*/EntityDataObjectName.csdl|  
  26.     res: //*/EntityDataObjectName.ssdl|  
  27.         res: //*/EntityDataObjectName.msl";  
  28.         return entityBuilder.ToString();  
  29. }  
This is the final connection string that returns by this method.
  1. <add name="DBEntities" connectionString="metadata=res://*/DB.csdl|res://*/DB.ssdl|res://*/DB.msl;provider=System.Data.SqlClient;provider connection string="data sourceServerName;initial catalog=DB_Name;persist security info=True;user id=DBUserID;password=DBUserPassword;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
Thirdly, we would use it for whatever we needed by initializing the object.
  1. var entityhelper = new EntityHelper();  
  2. var getConnString = entityhelper.GenerateConnectionStringEntity(_connectionString);  
  3. var dbentity = new DBName_Entities(getConnString);  
The first line has initialization. Second line gets the dynamically generated entity connection string and finally in the third line it is used in the entity data object.

At last after doing our work of inserting or updating query we call entity Save Method like this to transfer our data to the Database server.
  1. dbentity.SaveChanges();  
That's  all, hope you found it useful and helpful.

Note:
The dynamic connection string generator is not only used for entity connection string builder but you can also create a simple connection string.