Closed NeilN1 closed 2 years ago
There are a few ways. Have a read of these two articles.
I did read both articles before posting. Am I correct in thinking that only the second applies to the .tt file and I would have to manually change the environment variable every time I switch to a branch that connects to a different version of the database?
Hi Neil. Thanks for reading 👍
The second is only used for uat/production environments, and not for development as you can chop and change all the time.
I personally go for Settings.OnConfiguration = OnConfiguration.ConnectionString
for local development. The connection string is usually something simple like
.UseSqlServer(@"Data Source=(local);Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=True");
However, for your needs, in startup.cs
add in
services.AddDbContext<BackOfficeContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("BackOffice"));
});
or
var defaultConnection = this.Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<BackOfficeContext>(options =>
options.UseSqlServer(defaultConnection));
For an Azure function, you can pick it up from environment
class Startup : FunctionsStartup
{
public override void Configure(IFunctionsHostBuilder builder)
{
var sqlConnection = Environment.GetEnvironmentVariable("SQL_CONNECTION");
builder.Services.AddDbContext<BackOfficeContext>(
options => options.UseSqlServer(sqlConnection));
}
}
Your appsettings.json
will have the local connection string, and in appsettings.Production.json
you will have your production connection string, etc.
I'm using DI in .NET 6 and have Settings.OnConfiguration = OnConfiguration.Omit; so the connection string does not appear in the generated classes. But how do people handle the connection string appearing in plaintext in the tt file when pushing code to a repository?