You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

本地EF Core应用发布至Azure SQL数据库失败求助

解决方案

1. 移除硬编码连接字符串,改用配置文件读取

硬编码本地连接字符串是核心问题——部署到Azure后,应用仍会尝试连接本地SQL Server。修改DbContext的OnConfiguring方法,从配置文件读取连接字符串:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("NavbaseContext"));
    }
}

2. 在appsettings.json中配置Azure SQL连接字符串

登录Azure门户,找到你的Azure SQL数据库,复制ADO.NET格式的连接字符串,替换其中的{your_username}和{your_password}后,添加到appsettings.json:

{
  "ConnectionStrings": {
    "NavbaseContext": "Server=tcp:{your-server-name}.database.windows.net,1433;Initial Catalog=Navbase;Persist Security Info=False;User ID={your_username};Password={your_password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
  }
}

3. 配置Azure App Service的生产环境连接字符串

发布到Azure时,需在App Service中配置生产环境的连接字符串,避免代码中的配置泄露敏感信息:

  • 进入Azure App Service的「配置」→「连接字符串」
  • 添加名称为NavbaseContext的连接字符串,值填Azure SQL的完整连接字符串
  • 类型选择「SQLAzure」

4. 正确执行数据库更新命令

执行数据库更新时,确保命令指向Azure SQL数据库,可通过两种方式实现:

方式一:通过环境变量指定生产环境

Windows:

set ASPNETCORE_ENVIRONMENT=Production
dotnet ef database update --context Project1.Models.NavbaseContext

Linux/macOS:

export ASPNETCORE_ENVIRONMENT=Production
dotnet ef database update --context Project1.Models.NavbaseContext

方式二:命令行直接传递连接字符串

dotnet ef database update --context Project1.Models.NavbaseContext --connection "Server=tcp:{your-server-name}.database.windows.net,1433;Initial Catalog=Navbase;User ID={your_username};Password={your_password};Encrypt=True;"

5. 验证Azure SQL的访问权限

确保Azure SQL服务器的防火墙规则允许以下访问:

  • 添加本地机器的IP地址(执行dotnet ef命令时需要)
  • 勾选「允许Azure服务和资源访问此服务器」(让App Service能连接数据库)

内容的提问来源于stack exchange,提问作者Yugraaj Sandhu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:37:39