Click here to Skip to main content
15,897,371 members
Articles / .NET
Tip/Trick

Set the connection string for Entity Framework at runtime

Rate me:
Please Sign up or sign in to vote.
3.85/5 (20 votes)
2 Aug 2011CPOL 160.1K   12   16
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)


Written By
Web Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
I hold a BS degree in software engineering and am a Microsoft Certified Solution Developer(MCSD).
I have more than 8 years of experience in .NET developement, mostly web develop using C# and ASP.NET.

Comments and Discussions

 
QuestionExcellent!! Pin
Member 42609687-Apr-14 13:27
Member 42609687-Apr-14 13:27 
GeneralThanks. Pin
CIAP10-Jun-13 10:48
CIAP10-Jun-13 10:48 
QuestionFor Entity Framework Pin
aomidi5-Feb-13 0:53
aomidi5-Feb-13 0:53 
GeneralMy vote of 2 Pin
Michael Freidgeim15-Nov-12 8:03
Michael Freidgeim15-Nov-12 8:03 
QuestionIs esb required? Pin
Michael Freidgeim15-Nov-12 7:49
Michael Freidgeim15-Nov-12 7:49 
GeneralMy vote of 5 Pin
eibbed7-Sep-12 11:07
eibbed7-Sep-12 11:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.