Generate ADO.Net Entity Framework Connection String on RunTime
When application uses ADO.Net Entity framework, by default connection string saves in web.config file. We can delete the default connection string from web.config file and pass the connection string to the context object as follows.
using System.Data.SqlClient;
using System.Data.EntityClient;
//ConnectionString would be normal sql connection string
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(connectionString);
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = "System.Data.SqlClient";
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = @"res://*/Entities.csdl|res://*/ Entities.ssdl|res://*/ Entities.msl";
EntityConnection conn = new EntityConnection(entityBuilder.ToString());
using (Entities context = new Entities(conn))
{
//Your code ..
}
Comments