.NET Core 无法连接到 SQL 数据库。

12

我使用.NET Core Web API连接到SQL数据库。我在连接API和数据库时遇到了问题,我尝试了一个本地数据库"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 Object Explorer连接到两个数据库。我还有一个工作的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")));

应用程序设置.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)

Error: 50 - The given name from the LocalDB instance is not valid.:"Der angegebene Name der LocalDB-Instanz ist ungültig."

Scaffold Error (远程数据库)

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 - 找不到指定的服务器/实例


编辑:

可能是重复问题,参见无法远程连接到SQL Server实例? 能够连接到远程数据库,只有Core存在问题。

Visual Studio SQL Server Object Explorer Advanced Properties


1
不,我只想连接远程数据库。但是我已经尝试了所有方法 :/ - Janneck Lange
对于具有用户名和密码的远程服务器,您可以尝试使用“Data Source =”而不是“Server =”。 - DTul
@Burk 不是很对,看下面 - Janneck Lange
这两个问题看起来很相似,以下是我的问题所在。https://stackoverflow.com/a/60703731/3411340 - Burk
我的 MySQL 服务器托管在本地网络中,我在连接字符串中使用了该机器的固定 IP 地址,但有一天早上,尽管固定 IP 地址没有更改,我的应用程序无法访问数据库。我将其配置为基于主机名连接,现在连接又正常了。我太累了,无法理解为什么会发生这种情况,但对于其他人来说:如果您遇到此问题,请尝试在 IP 地址和主机名之间切换... :( - Superman.Lopez
显示剩余17条评论
3个回答

13

在我的情况下,数据库可通过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

我按照这个链接设置了数据库实例的端口号。

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

因此,将连接字符串更改为以下内容:

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

我也遇到了同样的问题,我使用的是 localhost:1433,但由于某些原因应该改为 localhost,1433 - Sudara
我已经为了让这个工作而苦恼了一整天。非常感谢!端口引用是解决我的问题的关键! - LostLogic

3
我们遇到了类似(或完全相同的)问题。 .NET Core不能使用连接字符串,但.NET Framework可以使用相同的字符串。原因是我们的连接字符串使用的是SQL别名而不是数据库服务器的IP主机名,而.NET Core放弃了SQL别名支持,因为它太过于Windows/注册表。将连接字符串更改为使用IP主机名或数字解决了该问题。

1
在这种情况下的问题是实例Server=192.168.1.XXX\\SQL2012;。我不知道为什么,但系统无法处理它。我改用另一个没有实例的服务器。
欢迎提供真正的解决方案。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接