0

Is it possible to compose some xml entry in app.config (in my case some of connectionStrings) using appSettings parameters from the same file? Example:

  <connectionStrings>
    <add name="MyContextDB" connectionString="Data Source =.;Initial Catalog = EFMyContextDB;Integrated Security = false;User Id=user;Password=pwd" providerName="System.Data.SqlClient" />
  </connectionStrings>

  <appSettings>
    <add key="UserId" value="userValue" />
    <add key="Password" value="pwdValue" />
  </appSettings>

I want to somehow use UserId instead of user and Password instead of pwd values of MyContextDB's connectionString.

This connection is then used in DbContext object:

public class MyContext : DbContext
{
    public MyContext() : base("name = MyContextDB") { }
    ...
}

2 Answers 2

2

You certainly can look at using SqlConnectionStringBuilder. Pass your existing connection string in to the constructor. Set the Password and the UserID properties. Then call ToString().

You won't be able to pass the connection string like that for your DbContext. You could consider refactoring that to a factory pattern or something similar.

I would also consider using config transforms to actually update the config files at build time.

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

Comments

0

Use the SqlConnectionStringBuilder:

    System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder(System.Configuration.ConfigurationManager.ConnectionStrings["MyContextDB"].ToString());

    builder.UserID = System.Configuration.ConfigurationManager.AppSettings["UserId"];
    builder.Password = System.Configuration.ConfigurationManager.AppSettings["Password"];

Then, to get the new connectionstring:

builder.ToString();

2 Comments

isn't this what i said?
Sorry, I did not see your comment.

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.