Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / .NET

Set the connection string for Entity Framework at runtime

3.85/5 (20 votes)
2 Aug 2011CPOL 161.8K  
This shows how to set or change the connection string for Entity Framework at run time (programmatically)
C++
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)