sql-serverentity-framework-6console-applicationscaffolding

Use name connectionStrings in app.config for Scaffold-DbContext EF 6 command


I've a "litle" problem to scaffold an existing database from SQL Server using Entity Framework 6 in my console app...

My connection string in App.config is:

<connectionStrings>
    <add name="connString"
         connectionString="Server=MyServer; Database=MyDb;User Id=MYUser ; Password=MyPW ; MultipleActiveResultSets=true;" 
         providerName="System.Data.SqlClient"/>
</connectionStrings> 

If I try to scaffold my database with this command:

Scaffold-DbContext -Connection name=connString Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -force

or

Scaffold-DbContext -Connection name=connectionString Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -force

or

Scaffold-DbContext "Name=connectionStrings:connString" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Context MyDbContext -force

The console always returns an error:

A named connection string was used, but the name '.......' was not found in the application's configuration. Note that named connection strings are only supported when using 'IConfiguration' and a service provider, such as in a typical ASP.NET Core application. See https://go.microsoft.com/fwlink/?linkid=850912 for more information.

So I tried to scaffold using plaintext connection string, and it didn't return any errors, but only the suggestion:

To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.

So my question is:

What should I do to be able to write only the name of my connection string, rather than the connection string in clear text?

Thanks in advance


Solution

  • In my case (VS2022, .NET 6) I also encountered the same problem n got solution in following way;

    1. Added Connection String in appsettings.json file (Screenshot attached)
    2. Ran the command: PM> Scaffold-DbContext name=StudentDbConnectionString TrustServerCertificate=true;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
    3. It generated relevant DbContext file (Screenshot attached)
    4. Manually registered DbContext in Builder.Services in program.cs file (Screenshot attached)
    5. Rebuilt application
    6. Run application and all the previously implemented functionalities tested successfully. enter image description here