3

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>

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

Using the EntityConnectionStringBuilder is a much better approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.