.NET Core 无法连接到 SQL DB

Posted

技术标签:

【中文标题】.NET Core 无法连接到 SQL DB【英文标题】:.NET Core can´t connect to SQL DB 【发布时间】:2019-10-03 09:16:28 【问题描述】:

我构建了一个连接到 SQL DB 的新 .net Core Web API。我在将 API 与我的数据库连接时遇到问题我尝试了一个本地 DB "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB; Initial Catalog=ib; Integrated Security=SSPI", 和一个远程数据库(请参阅 appsettings.json)。

远程:Microsoft SQL Server Express(64 位)11.0.2100.60 系统:Microsoft Windows NT 6.1 (7601)

可以使用 SQL Server Management Studio 或 Visual Studio SQL Server 对象资源管理器连接到这两个数据库。我还有一个工作的 asp.net Web 应用程序,我在其中使用相同的(远程)连接字符串。

但是使用新的 Core Web API 我无法建立连接。没有下面的设置,也没有来自 NuGet 的 Scaffold-DBContext 连接

如果您需要更多我的代码,您可以询问。非常感谢您的帮助。

 Scaffold-DbContext "Connection String" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Startup.cs

 services.AddDbContext<ibContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

appsettings.json

"ConnectionStrings": 
    "DefaultConnection": "Server=192.168.1.XXX\\SQL2012; Initial Catalog=IBCOREDB_XXX; User ID=XXXX;Password=XXXXX;",
  ,

核心错误(远程数据库)

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.4\System.Diagnostics.StackTrace.dll'. Cannot find or open the PDB file.
'iisexpress.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\2.2.4\System.Reflection.Metadata.dll'. Cannot find or open the PDB file.
Microsoft.EntityFrameworkCore.Database.Connection:Error: An error occurred using the connection to database 'IBCOREDB_XXX' on server '192.168.1.XXX\SQL2012'.

System.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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at ...

错误:26 - 查找指定的服务器/实例时出错

支架错误(对于本地数据库)

System.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: SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Der angegebene Name der LocalDB-Instanz ist ungültig.
) ---> System.ComponentModel.Win32Exception (0x89C5011B): Unknown error (0x89c5011b)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)

错误:50 - LocalDB-Instanz 中的给定名称无效。:“Der angegebene Name der LocalDB-Instanz ist ungültig。”

支架错误(远程数据库)

System.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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken)

错误:26 - 查找指定的服务器/实例时出错


编辑:

可能从Unable to connect to SQL Server instance remotely 复制?可以连接到远程数据库,只有 Core 有问题。

【问题讨论】:

等等 - 所以你正试图同时连接到 2 个独立的数据库? 不,我只想连接远程数据库。但我什么都试过了:/ 看起来类似于这个问题:***.com/questions/6987709/… 对于具有用户和密码的远程服务器,您可以尝试使用Data Source= 而不是Server= Unable to connect to SQL Server instance remotely的可能重复 【参考方案1】:

在我的例子中,可以通过 ASP.NET Web API 和 Windows Forms 应用程序访问数据库。但是 .Net Core API 不起作用。

问题的解决方法是在连接字符串中添加端口号。

例如下面指定的连接字符串是 .NET Framework 应用程序的示例。

data source=SERVER\SQLSERVER2017;initial catalog=DBNAME;persist security info=True;user id=ADMIN;password=ADMIN123;MultipleActiveResultSets=True;App=EntityFramework

我按照this 链接为数据库实例设置端口号。

逗号后面的端口号是关键。

所以把连接字符串改成这样:

Server=SERVER\\SQLSERVER2017,1433;Database=DBNAME;User Id=ADMIN; Password=ADMIN123;MultipleActiveResultSets=True;

【讨论】:

同样的事情发生在我身上,我使用的是localhost:1433,但由于某种原因它应该是localhost,1433【参考方案2】:

我们遇到了类似(或相同?)的问题。 .NET Core 不适用于连接字符串,但 .NET Framework 可以正常使用相同的字符串。原来是因为我们的连接字符串使用的是 SQL Alias 而不是数据库服务器的 IP 主机名,而 .NET Core 放弃了对 SQL Alias 的支持,因为它过于 Windowsy/registry-y。

将连接字符串更改为使用 IP 主机名或编号解决了该问题。

.NET 团队讨论问题:https://github.com/dotnet/corefx/issues/2575 相关的 SO 问题:例如Issues with SQL Alias in ConnectionString in appsettings.json。

【讨论】:

【参考方案3】:

本例中的问题是实例Server=192.168.1.XXX\\SQL2012;。我不知道为什么,但系统无法处理它。我改用另一个服务器(没有实例)。

欢迎真正的解决方案。

【讨论】:

以上是关于.NET Core 无法连接到 SQL DB的主要内容,如果未能解决你的问题,请参考以下文章

Azure 上的 .NET Core 无法连接到 SQL Server 数据库

无法从在 Docker (Linux) 中运行的 ASP.NET Core 连接到 SQL Server 命名实例

无法从 NET Core 2.2 Web API 连接到 docker sql server

无法从在具有自定义运行时的 Docker 中运行 .NET Core 应用程序的 App Engine 连接到 Google Cloud SQL 中的 postgres

.Net Core ClientWebSocket:无法连接到服务器

Blazor 无法连接到 ASP.NET Core WebApi (CORS)