简体   繁体   中英

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. Following this tutorial but implementing in .NET 6.

Part of error log:

Entity Framework Core 6.0.7 initialized 'CommanderContext' using provider 'Microsoft.EntityFrameworkCore.SqlServer:6.0.7' with options: None
fail: Microsoft.EntityFrameworkCore.Database.Connection[20004]

An error occurred using the connection to database 'CommanderDB' on server 'localhost'.

fail: Microsoft.EntityFrameworkCore.Query[10100]
An exception occurred while iterating over the results of a query for context type 'Commander.Data.CommanderContext'.
Microsoft.Data.SqlClient.SqlException (0x80131904): 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: 40 - Could not open a connection to SQL Server: Could not open a connection to SQL Server)

Connection string in appsettings.json , checked and matched with server explorer database property. Checked SQL Server was running in Configuration Manager and able to be accessed in SSMS. Executing dotnet ef migrations add successfully connects and also created table. Remote connections are enabled.

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

Connecting in Program.cs with this code:

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

EDIT:

SQL Server Protocols SS

Shared Memory and TCP enabled.

Resolved, was running on docker so it wasn't able to connect to localhost. Switch to (project name). Dropdown split button options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM