无Startup/HostBuilder时,如何将EF连接字符串移至appSettings.<env>.json?
最简方法:将EF硬编码连接字符串迁移至appSettings.json
1. 添加配置文件
- 在项目根目录创建
appSettings.json文件;若需区分开发/生产环境,额外创建appSettings.Development.json - 右键配置文件 → 属性 → 设置复制到输出目录为「如果较新则复制」或「始终复制」
2. 写入连接字符串
在appSettings.json中添加连接字符串节点:
{ "ConnectionStrings": { "DefaultConnection": "Host=localhost;Port=5432;Database=...;Username=...;Password=..." } }
若需针对开发环境单独配置,在appSettings.Development.json中覆盖DefaultConnection的值即可。
3. 修改EfContext读取配置
更新OnConfiguring方法,手动加载配置文件并读取连接字符串:
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using System.IO; public partial class EfContext : DbContext { protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { // 构建配置对象,自动读取环境对应的配置文件 var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appSettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true) .Build(); // 读取连接字符串并配置EF string connectionString = configuration.GetConnectionString("DefaultConnection"); optionsBuilder.UseNpgsql(connectionString); } } }
执行以下命令安装所需NuGet包:
Install-Package Microsoft.Extensions.Configuration.Json
4. 迁移命令的环境切换(可选)
若要指定环境运行迁移,在命令行设置环境变量后执行迁移命令:
- Windows(CMD):
set ASPNETCORE_ENVIRONMENT=Development dotnet ef database update
- Windows(PowerShell):
$env:ASPNETCORE_ENVIRONMENT = "Development" dotnet ef database update
- Linux/macOS:
export ASPNETCORE_ENVIRONMENT=Development dotnet ef database update
内容的提问来源于stack exchange,提问作者Dagrada
相关产品推荐
相关产品推荐

