Home > Back-end >  EF Core Reading Connection String From User Secret Using Class Library Project and DB Scaffolding
EF Core Reading Connection String From User Secret Using Class Library Project and DB Scaffolding

Time:01-11

I have two projects, one is the Web and the Other a Class Library. I need to put Entity Framework in the Class Library Project. However, I am unable to read the Connection String when scaffolding the DB.

  1. Initialize Secret: dotnet user-secrets init
  2. Set item to store: dotnet user-secrets set "ConnectionStrings:MyConnString" "string"
  3. Scaffold DB: dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString

This obviously will not work because the static configuration method is in the web project and not the Class Library project.

Error: A named connection string was used, but the name 'ConnectionStrings:APIConnection' was not found in the application's configuration.

The only way I can make this work is hardcoding the connection string.

Is there anyway other way to make this work?

CodePudding user response:

It works for me in ASP.NET Core 6 and EfCore v6.0.1.

Here the steps I've done:

  1. Create ASP.NET Core Web API and class lib projects
-- > WebApp.Api\
   |
   > WebApp.Data\ 
   |
   > WebApp.sln
  1. Set connection string secret for WebApp.Api. Ensure that UserSecretsId is added to csproj PropertyGroup:
> dotnet user-secrets init
> dotnet user-secrets set "ConnectionStrings:MyConnString" "<conn-string>"
  1. Install Microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.SqlServer into WebApp.Data. Add project reference from WebApp.Api to WebApp.Data.
  2. Install Microsoft.EntityFrameworkCore.Design nuget for WebApp.Api project.
  3. In cmd navigate to WebApp.Api project folder and run the following command:
> dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString "Microsoft.EntityFrameworkCore.SqlServer" -p ..\WepApp.Data\ 

In that case for the scaffold command startup project is WebApp.Api and target project is WebApp.Data

  •  Tags:  
  • Related