EF Core 使用 Class 库项目和数据库脚手架从用户密码中读取连接字符串
EF Core Reading Connection String From User Secret Using Class Library Project and DB Scaffolding
我有两个项目,一个是 Web,另一个是 Class 库。
我需要将 Entity Framework 放入 Class 图书馆项目中。
但是,搭建数据库时我无法读取连接字符串。
- 初始化秘密:
dotnet user-secrets init
- 设置要存储的项目:
dotnet user-secrets set "ConnectionStrings:MyConnString" "string"
- 脚手架数据库:
dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString
这显然行不通,因为静态配置方法是在web项目而不是Class库项目中。
错误:
A named connection string was used, but the name 'ConnectionStrings:APIConnection' was not found in the application's configuration.
我能完成这项工作的唯一方法是对连接字符串进行硬编码。
还有其他方法可以实现吗?
它适用于 ASP.NET Core 6 和 EfCore v6.0.1
。
这是我完成的步骤:
- 创建 ASP.NET Core Web API 和 class lib 项目
-- > WebApp.Api\
|
> WebApp.Data\
|
> WebApp.sln
- 为
WebApp.Api
设置连接字符串机密。确保 UserSecretsId
添加到 csproj PropertyGroup
:
> dotnet user-secrets init
> dotnet user-secrets set "ConnectionStrings:MyConnString" "<conn-string>"
- 将
Microsoft.EntityFrameworkCore
和 Microsoft.EntityFrameworkCore.SqlServer
安装到 WebApp.Data
。将项目引用从 WebApp.Api
添加到 WebApp.Data
。
- 为
WebApp.Api
项目安装 Microsoft.EntityFrameworkCore.Design
nuget。
- 在 cmd 中导航到
WebApp.Api
项目文件夹和 运行 以下命令:
> dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString "Microsoft.EntityFrameworkCore.SqlServer" -p ..\WepApp.Data\
在这种情况下,scaffold
命令启动项目是 WebApp.Api
,目标项目是 WebApp.Data
我有两个项目,一个是 Web,另一个是 Class 库。 我需要将 Entity Framework 放入 Class 图书馆项目中。 但是,搭建数据库时我无法读取连接字符串。
- 初始化秘密:
dotnet user-secrets init
- 设置要存储的项目:
dotnet user-secrets set "ConnectionStrings:MyConnString" "string"
- 脚手架数据库:
dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString
这显然行不通,因为静态配置方法是在web项目而不是Class库项目中。
错误:
A named connection string was used, but the name 'ConnectionStrings:APIConnection' was not found in the application's configuration.
我能完成这项工作的唯一方法是对连接字符串进行硬编码。
还有其他方法可以实现吗?
它适用于 ASP.NET Core 6 和 EfCore v6.0.1
。
这是我完成的步骤:
- 创建 ASP.NET Core Web API 和 class lib 项目
-- > WebApp.Api\
|
> WebApp.Data\
|
> WebApp.sln
- 为
WebApp.Api
设置连接字符串机密。确保UserSecretsId
添加到 csprojPropertyGroup
:
> dotnet user-secrets init
> dotnet user-secrets set "ConnectionStrings:MyConnString" "<conn-string>"
- 将
Microsoft.EntityFrameworkCore
和Microsoft.EntityFrameworkCore.SqlServer
安装到WebApp.Data
。将项目引用从WebApp.Api
添加到WebApp.Data
。 - 为
WebApp.Api
项目安装Microsoft.EntityFrameworkCore.Design
nuget。 - 在 cmd 中导航到
WebApp.Api
项目文件夹和 运行 以下命令:
> dotnet ef dbcontext scaffold Name=ConnectionStrings:MyConnString "Microsoft.EntityFrameworkCore.SqlServer" -p ..\WepApp.Data\
在这种情况下,scaffold
命令启动项目是 WebApp.Api
,目标项目是 WebApp.Data