Entity Framework Core怎么配置连接字符串 EF Core appsettings.json配置方法

EF Core 最常用连接字符串配置方式是通过 appsettings.json 管理,并在 Program.cs(.NET 6+)或 Startup.cs(.NET 5 及以前)中读取注入 DbContext;需在 ConnectionStrings 节点下定义键值对,如 “DefaultConnection”,并在 DbContext 配置或服务注册时使用 IConfiguration 获取并传入;支持多环境配置(如 appsettings.Development.json),生产环境应避免硬编码敏感信息,推荐使用环境变量或密钥管理服务。

entity framework core怎么配置连接字符串 ef core appsettings.json配置方法

在 EF Core 中配置连接字符串,最常用的方式是通过 appsettings.json 文件管理,并在 Startup.cs(.NET 5 及以前)或 Program.cs(.NET 6+)中读取并注入到 DbContext

appsettings.json 中定义连接字符串

打开项目根目录下的 appsettings.json,在 "ConnectionStrings" 节点下添加你的数据库连接字符串。例如:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)//mssqllocaldb;Database=MyAppDb;Trusted_Connection=true;MultipleActiveResultSets=true"
  }
}

注意:
– 键名(如 DefaultConnection)可自定义,后续代码中需保持一致;
– 不同数据库的连接字符串格式不同(SQL Server、PostgreSQL、SQLite 等),请按实际数据库调整;
– 生产环境建议把敏感信息(如密码)用 User Secrets环境变量替代,不要硬编码

在 DbContext 中使用 IConfiguration 注入连接字符串

确保你的 DbContext 构造函数接收 IConfiguration 或直接接收连接字符串。推荐方式是传入 IConfiguration,然后在内部获取:

public class AppDbContext : DbContext
{
    private readonly IConfiguration _configuration;

    public AppDbContext(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        var connectionString = _configuration.GetConnectionString("DefaultConnection");
        options.UseSqlServer(connectionString);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 配置模型...
    }
}

或者更现代的做法(推荐):在 Program.cs 中注册上下文时直接传入连接字符串:

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext(options =>
    options.UseSqlServer(connectionString));

环境配置(开发/生产)

EF Core 自动支持 appsettings.{Environment}.json 分离配置。比如:

  • appsettings.Development.json:本地调试用的 LocalDB 或 SQLite
  • appsettings.Production.json:指向云数据库,含账号密码(建议配合 Azure Key Vault 或环境变量)

只要 ASPNETCORE_ENVIRONMENT 环境变量设置正确(如 Production),EF Core 就会自动合并对应文件中的配置。

Vondy

Vondy

下一代AI应用平台,汇集了一流的工具/应用程序

下载

验证连接是否生效

启动应用后,可以加一行日志或断点检查连接字符串是否读取成功:

Console.WriteLine($"ConnStr: {_configuration.GetConnectionString("DefaultConnection")}");

也可以运行迁移命令测试:

  • dotnet ef migrations add InitialCreate
  • dotnet ef database update

如果报错 “Keyword not supported: ‘server’”,通常是连接字符串格式错误或未正确加载;如果提示找不到连接字符串,则检查键名拼写和 JSON 层级是否正确(必须在 ConnectionStrings 下)。

基本上就这些。配置本身不复杂,但容易忽略大小写、JSON 缩进、环境匹配等细节。

https://www.php.cn/faq/1982153.html

发表回复

Your email address will not be published. Required fields are marked *