Reputation: 1633
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") { }
...
}
Upvotes: 0
Views: 691
Reputation: 190905
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.
Upvotes: 2
Reputation: 2206
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();
Upvotes: 0