簡體   English   中英

NET 6 - 實體框架核心錯誤:SQL 服務器未找到或無法訪問

[英]NET 6 - Entity Framework Core Error: SQL Server was not found or was not accessible

I am creating an ASP.NET Core 6 Web API (VS 2022), and executing any controller API through swagger ui results in a connection to SQL Server error. 遵循本教程,但在 .NET 6 中實施。

部分錯誤日志:

Entity Framework Core 6.0.7 使用提供者“Microsoft.EntityFrameworkCore.SqlServer:6.0.7”初始化“CommanderContext”,選項:無
失敗:Microsoft.EntityFrameworkCore.Database.Connection[20004]

使用與服務器“localhost”上的數據庫“CommanderDB”的連接時發生錯誤。

失敗:Microsoft.EntityFrameworkCore.Query[10100]
迭代上下文類型“Commander.Data.CommanderContext”的查詢結果時發生異常。
Microsoft.Data.SqlClient.SqlException (0x80131904):與 SQL 服務器建立連接時發生與網絡相關或特定於實例的錯誤。 服務器未找到或無法訪問。
驗證實例名稱是否正確,並且 SQL 服務器配置為允許遠程連接。 (提供程序:TCP 提供程序,錯誤:40 - 無法打開與 SQL 服務器的連接:無法打開與 SQL 服務器的連接)

appsettings.json中的連接字符串,檢查並與服務器資源管理器數據庫屬性匹配。 檢查 SQL 服務器在配置管理器中運行並且能夠在 SSMS 中訪問。 執行dotnet ef migrations add成功連接並創建表。 遠程連接已啟用。

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "CommanderConnection": "Data Source=localhost;Initial Catalog=CommanderDB;User ID=CommanderAPI;Password=1234;"
  }
}

使用以下代碼在Program.cs中連接:

builder.Services.AddDbContext<CommanderContext>(opt => opt.UseSqlServer(builder.Configuration.GetConnectionString("CommanderConnection")));
builder.Services.AddScoped<ICommanderRepo, SqlCommanderRepo>(); 

編輯:

SQL 服務器協議 SS

共享 Memory 和 TCP 已啟用。

已解決,在 docker 上運行,因此無法連接到 localhost。 切換到(項目名稱)。 下拉拆分按鈕選項

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM