Internet Engineer
Internet Engineer

Reputation: 2534

Dynamically Create DB Connection String for Entity in MVC 4

I have an entity in MVC 4 project and the connection string is placed in the web.config by the entity creation wizard.

I need to change this and assign the password to the connection string (which is stored outside the web.config) at run time.

  1. How can I combine values outside the web.config with a string stored inside the web.config?

  2. Or can I move the entity connection completely outside the web.config?

This is the existing entity connection string:

add name="MyEntities" connectionString="metadata=res://*/Models.NewUsers.csdl|res://*/Models.NewUsers.ssdl|res://*/Models.NewUsers.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=mydb;initial catalog=MyDatabase;persist security info=True;user id=sa;password=Mypassword;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /></connectionStrings>

Upvotes: 3

Views: 2527

Answers (2)

Craig Stuntz
Craig Stuntz

Reputation: 126547

For 2, you can always pass a new connectionString (not from web.config) directly to the context when you create it:

string newCS = "add name=...";
var context = new MyEntities(newCS);

For 1, use EntityConnectionStringBuilder to parse an existing CS or build a new one.

Upvotes: 3

Peter Smith
Peter Smith

Reputation: 5550

A simple solution might be to use something based on:

string con = ConfigurationManager.ConnectionStrings["PerinatalDataEntities"].
    ConnectionString;
con = con.replace("user id=sa", "user id=MyUser").
    Replace("password=Mypassword","password=MyNewpassword")

I believe there is also a connection builder but I've never used it.

Upvotes: 1

Related Questions