简体   繁体   中英

C# compose connectionString in app.config using appSettings parameters

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") { }
    ...
}

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM