65.9K
CodeProject is changing. Read more.
Home

Set the connection string for Entity Framework at runtime

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.85/5 (20 votes)

Aug 2, 2011

CPOL
viewsIcon

161767

This shows how to set or change the connection string for Entity Framework at run time (programmatically)

string connectionString = new System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);

System.Data.SqlClient.SqlConnectionStringBuilder scsb = new System.Data.SqlClient.SqlConnectionStringBuilder(connectionString);

EntityConnectionStringBuilder ecb = new EntityConnectionStringBuilder();
ecb.Metadata = "res://*/Sample.csdl|res://*/Sample.ssdl|res://*/Sample.msl";
ecb.Provider = "System.Data.SqlClient";
ecb.ProviderConnectionString = scsb.ConnectionString;

dataContext = new SampleEntities(ecb.ConnectionString);
This also would be useful if you want to encrypt the connection string using your own methods.