VS Code 数据库连接字符串

问题描述 投票:0回答:1

问题:

在 VS Code 中,我使用实体框架创建了一个 .NET Web API 应用程序。要激活 .NET 命令,我始终必须运行以下命令:

export PATH="$PATH:$HOME/.dotnet/tools"

完成此操作后,我可以成功运行迁移。但是,迁移后,当我尝试使用以下命令更新数据库时:

dotnet ef database update

我收到以下错误:

A network-related or instance-specific error occurred while establishing a connection to SQL Server.
The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. 
(provider: TCP Provider, error: 26 - Error Locating Server/Instance Specified)

appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=Khashayar\\SQLEXPRESS;Initial Catalog=FinanceNews;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Program.cs注入:

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

已安装的软件包:

  • Microsoft.AspNetCore.OpenApi 8.0.8
  • Microsoft.EntityFrameworkCore.Design 8.0.8
  • Microsoft.EntityFrameworkCore.SqlServer 8.0.8
  • Microsoft.EntityFrameworkCore.Tools 8.0.8

附加信息:

  • 我正在使用 Ubuntu 终端。
  • 我正在使用 .NET 8、SQL Server Management Studio (SSMS) 20 和 SQL Server 2022 配置管理器。
  • 在SSMS中,我检查了“信任服务器证书”,并且加密设置为强制模式。
  • 服务正在运行,并且数据源名称正确(我通过在终端中运行
    hostname
    验证了这一点)。

采取的故障排除步骤:

  1. 我启用了 TCP/IP,但不起作用。

  2. 我尝试将数据源设置为

    KHASHAYAR\\SQLEXPRESS
    ,但没有成功。

  3. 我也尝试了

    KHASHAYAR\\khash\\SQLEXPRESS
    ,但也没成功。

  4. 我安装了必要的工具:

    sudo apt-get update
    sudo apt-get install mssql-tools unixodbc-dev
    echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
    source ~/.bashrc
    

    但是还是没有成功。我需要帮助才能使更新命令正常工作

截图:

c# asp.net-core entity-framework-core connection-string
1个回答
0
投票

作为解决方案,我建议使用更新命令并直接指定连接字符串:

dotnet ef database update --connection '"Data Source=Khashayar\\SQLEXPRESS;Initial Catalog=FinanceNews;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"'

在哪里寻找潜在问题:

  • 如果您引用 EF 的项目不是 appsettings 的主项目,您可能需要在 dotnet 命令中指示启动项目:
    dotnet ef database update --startup-project {project with appsettings}
    
  • 确保您可以使用某些客户端工具(Sql Management Studio 或其他工具,或从命令行尝试 ping)连接到数据库服务器
© www.soinside.com 2019 - 2024. All rights reserved.