c# - Entity Framework Core 通过 SSH 隧道连接到 MSSQL 数据库

标签 c# sql-server database-connection entity-framework-core connection-string

我看过很多帖子问类似的问题,但没有一个能解决我的问题。

我的设置如下:

  • 具有数据库的远程主机:可在 127.0.0.1:1433
  • 上访问
  • SSH 隧道:L5000 -> 127.0.0.1:1433

当我在 SQL Management Studio 中输入服务器名称 127.0.0.1,5000 时,我可以连接到我想要的数据库。

如果相应地调整我的连接字符串并启动我的应用程序,我会得到以下异常:

Type       : SqlException
Message    : 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Source     : Core .Net SqlClient Data Provider
HResult    : -2146232060
TargetSite : .ctor
----- INNER EXCEPTION -----
Type       : Win32Exception
Message    : The system cannot find the file specified
HResult    : -2147467259

由于我可以通过 Management Studio 进行连接,我认为问题出在我的连接字符串或与 Entity Framework Core 相关的问题上。以下是我测试过的一些连接字符串:

Data Source=127.0.0.1,5000;Network Library=DBMSSOCN;Initial Catalog=Mux;Integrated Security=False;Persist Security Info=False;User ID=...;Password=...;MultipleActiveResultSets=True;Connect Timeout=5;Encrypt=True;TrustServerCertificate=True;Application Name=Mux;ConnectRetryCount=3;ConnectRetryInterval=5
Data Source=127.0.0.1;port=5000;Network Library=DBMSSOCN;Initial Catalog=Mux;Integrated Security=False;Persist Security Info=False;User ID=...;Password=...;MultipleActiveResultSets=True;Connect Timeout=5;Encrypt=True;TrustServerCertificate=True;Application Name=Mux;ConnectRetryCount=3;ConnectRetryInterval=5
Server=127.0.0.1;port=5000;Network Library=DBMSSOCN;Initial Catalog=Mux;Integrated Security=False;Persist Security Info=False;User ID=...;Password=...;MultipleActiveResultSets=True;Connect Timeout=5;Encrypt=True;TrustServerCertificate=True;Application Name=Mux;ConnectRetryCount=3;ConnectRetryInterval=5
Server=127.0.0.1,5000;Initial Catalog=Mux;Integrated Security=False;Persist Security Info=False;User ID=...;Password=...;MultipleActiveResultSets=True;Connect Timeout=5;Encrypt=True;TrustServerCertificate=True;Application Name=Mux;ConnectRetryCount=3;ConnectRetryInterval=5
Server=127.0.0.1;port=5000;Initial Catalog=Mux;Integrated Security=False;Persist Security Info=False;User ID=...;Password=...;MultipleActiveResultSets=True;Connect Timeout=5;Encrypt=True;TrustServerCertificate=True;Application Name=Mux;ConnectRetryCount=3;ConnectRetryInterval=5
Server=tcp,127.0.0.1,5000;Initial Catalog=Mux;Integrated Security=False;Persist Security Info=False;User ID=...;Password=...;MultipleActiveResultSets=True;Connect Timeout=5;Encrypt=True;TrustServerCertificate=True;Application Name=Mux;ConnectRetryCount=3;ConnectRetryInterval=5

有人知道这是为什么吗?


编辑 1 我进行了更多测试;如果我尝试启动我的应用程序,SQL Server Profiler 不会注册任何事件。

此外,我尝试了 this 中的方法发布 .. 使用 ... tcp: ... 而不是 ... tcp, ... .. 这也没有用。

我尝试在 Visual Studio 中添加数据源 - 测试连接:好的。我什至复制了那里显示的连接字符串,将其粘贴到我的应用程序中,启动了它——没有用。只是说:是的,应用程序确实使用提供的连接字符串。

Visual Studio 和 SQL Management Studio 是否以不同于使用连接字符串的特殊方式连接到服务器?


编辑 2 根据您的评论,我想添加以下信息:

项目依赖:

  • Microsoft.EntityFrameworkCore.SqlServer v2.0.3
  • Microsoft.EntityFrameworkCore.Tools v2.0.3
  • Microsoft.VisualStudio.Web.CodeGeneration.Design v2.0.4

完整的日志信息:

Type       : SqlException
Message    : 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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Source     : Core .Net SqlClient Data Provider
HResult    : -2146232060
TargetSite : .ctor
Stacktrace : at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerDatabaseCreator.<>c__DisplayClass18_0.<Exists>b__0(DateTime giveUp)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s)
   at Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, Func`2 operation, Func`2 verifySucceeded, TState state)
   at Microsoft.EntityFrameworkCore.Migrations.HistoryRepository.Exists()
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at ch.wuerth.tobias.mux.Data.DataContextFactory.GetInstance()
   at ch.wuerth.tobias.mux.plugins.PluginMusicBrainz.PluginMusicBrainz.Process(String[] args) in C:\Users\Tobias\Desktop\dev\mux-cli\plugins\PluginMusicBrainz\PluginMusicBrainz.cs:line 136
   at ch.wuerth.tobias.mux.Core.plugin.PluginBase.Work(String[] args)
   at ch.wuerth.tobias.mux.App.Program..ctor(String[] args) in C:\Users\Tobias\Desktop\dev\mux-cli\App\Program.cs:line 47
Data :
 -> [HelpLink.ProdName, Microsoft SQL Server]
 -> [HelpLink.EvtSrc, MSSQLServer]
 -> [HelpLink.EvtID, 2]
 -> [HelpLink.BaseHelpUrl, http://go.microsoft.com/fwlink]
 -> [HelpLink.LinkId, 20476]
----- INNER EXCEPTION -----
Type       : Win32Exception
Message    : The system cannot find the file specified
HResult    : -2147467259

(内部异常没有堆栈跟踪,因为它一定是未定义的)

我的 DbContext 像这样初始化连接字符串:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("..my connection string..");
}

编辑 3 我现在高度认为问题一定出在 DbContext 的初始化上,否则如何解释 MSSQL Studio 和应用程序的不同行为。

还有那些寻求一些上下文的人: 我正在开发这个应用程序。除了本地开发环境外,我还有部署主分支的生产服务器。在生产服务器上还有一个独立的数据库,其中包含人们所期望的生产数据。我遇到的问题是,我在生产服务器上用于数据操作(导入、处理等)的 CLI 抛出了一个由数据引起的异常,我无法在我的开发环境中重现该错误。我没有尝试复制整个数据库(几千兆字节),而是尝试从我的开发环境中连接到生产数据库。这将允许我调试异常并解决问题。也许有人对如何使用实时数据库调试我的应用程序有另一种想法?

最佳答案

您的错误信息包含:

(provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

您是否打开了“SQL Server 配置管理器”并确保启用了“命名管道”?此设置位于 3 个位置。

关于c# - Entity Framework Core 通过 SSH 隧道连接到 MSSQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50174134/

相关文章:

c# - 如何形成正确的MySQL连接字符串?

java - Java 数据连接对话框

sql - 我如何以规范化的方式存储联系方式(或具有不同字段的类似类型的数据)?

sql - 如何让字符串自动递增

c# - web.config、web.debug.config、web.release.config 和发布与调试?

C#扫描特定 block 的图像

sql - 显示两个日期之间的所有日期数据;如果特定日期不存在行,则所有列中显示零

mysql - PDO:连接到数据库服务器(不是特定的数据库名称)

c# - 长时间运行 WCF 504 GATEWAY_TIMEOUT 错误

C# - 替代 Silverlight 中的 .NET ArrayList.ToArray(Type)