简体   繁体   English

C#使用appSettings参数在app.config中撰写connectionString

[英]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? 是否可以使用同一文件中的appSettings参数在app.config组成一些xml条目(在我的情况下是一些connectionStrings )? 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 . 我想以某种方式使用UserId代替userPassword代替MyContextDB's connectionStringpwd值。

This connection is then used in DbContext object: 然后在DbContext对象中使用此连接:

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

You certainly can look at using SqlConnectionStringBuilder . 您当然可以看看使用SqlConnectionStringBuilder Pass your existing connection string in to the constructor. 将现有的连接字符串传递给构造函数。 Set the Password and the UserID properties. 设置PasswordUserID属性。 Then call ToString() . 然后调用ToString()

You won't be able to pass the connection string like that for your DbContext . 您将无法像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. 我还将考虑使用config转换在构建时实际更新配置文件。

Use the SqlConnectionStringBuilder: 使用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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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