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

Popular posts from this blog

Windows Azure Package Build Error: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

Resource ID : 1. The request limit for the database is 180 and has been reached.

How to get Client's Location using IPAddress