sjh37 / EntityFramework-Reverse-POCO-Code-First-Generator

EntityFramework Reverse POCO Code First Generator - Beautifully generated code that is fully customisable. This generator creates code as if you reverse engineered a database and lovingly created the code by hand. It is free to academics (you need a .edu or a .ac email address), not free for commercial use. Obtain your licence from
https://www.reversepoco.co.uk/
Other
706 stars 230 forks source link

Connectionstring in tt file #766

Closed NeilN1 closed 2 years ago

NeilN1 commented 2 years ago

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?

sjh37 commented 2 years ago

There are a few ways. Have a read of these two articles.

NeilN1 commented 2 years ago

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?

sjh37 commented 2 years ago

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));
    }
}
sjh37 commented 2 years ago

Your appsettings.json will have the local connection string, and in appsettings.Production.json you will have your production connection string, etc.