我已经解决这个问题近两天了,我已经没有选择了。也许你们可以帮忙。
背景:我将 .netcore api 从 Windows 迁移到 WSL2 (Ubuntu 20.04)。我的数据库在 Windows 上运行。当尝试运行
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: SQL Network Interfaces, error: 25 - Connection string is not valid: Connection string is not valid)
我的连接字符串(ip 是占位符):
"Server=192.168.0.1,1433/SQLEXPRESS,1433;Database=MyDatabase;Integrated Security=True;MultipleActiveResultSets=True;Encrypt=no"
我已经用谷歌搜索了该错误并尝试(或已经完成)了许多建议的解决方案,包括:
在 Windows 端使用 powershell 我运行了以下命令:
$sqlConn = New-Object System.Data.SqlClient.SqlConnection
$sqlConn.ConnectionString = "Server=localhost,1433;Database=MyDatabase;Encrypt=no;TrustServerCertificate=True;User ID=sa;Password='';Integrated Security=True;MultipleActiveResultSets=True"
$sqlConn
它打印出所有正确的信息。省略
Encrypt=no
将会出现错误 40,该错误与自签名 ssl 证书相关。省略用户 ID 和密码仍然可以成功连接。
我错过了什么?
如果您使用固定端口,则需要删除实例名称。您当然不应该在实例名称后指定端口。
SQL 身份验证使用
Integrated Security=False
。如果是 true
,那么它使用 Windows 身份验证,并且传递用户名和密码是没有意义的。您无法从 WSL 使用 Windows 身份验证。
Server=192.168.0.1,1433;Database=MyDatabase;MultipleActiveResultSets=True;User ID=sa;Password=''
如果确实有必要,请添加
TrustServerCertificate=True
,请注意这是一个安全风险。