连接到 SQL Server 时出现与网络相关或实例特定的错误 - ASP.NET MVC Entity Framework

11

我正在使用ASP.Net MVC 3(Entity Framework)和Sql Server 2008。连接字符串在web.config中正确配置。但有时我的应用程序会抛出以下异常:

    System.Data.SqlClient.SqlException: 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)

Generated: Wed, 02 May 2012 05:05:21 GMT

System.Data.EntityException: The underlying provider failed on Open. ---> System.Data.SqlClient.SqlException: 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)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity)
   at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, SqlConnection owningObject)
   at System.Data.SqlClient.SqlInternalConnectionTds.LoginWithFailover(Boolean useFailoverHost, ServerInfo primaryServerInfo, String failoverHost, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, TimeoutTimer timeout)
   at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, TimeoutTimer timeout, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
   at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnection owningConnection, DbConnectionPool pool, DbConnectionOptions options)
   at System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionPool.GetConnection(DbConnection owningObject)
   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
   at System.Data.SqlClient.SqlConnection.Open()
   at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
   --- End of inner exception stack trace ---
   at System.Data.EntityClient.EntityConnection.OpenStoreConnectionIf(Boolean openCondition, DbConnection storeConnectionToOpen, DbConnection originalConnection, String exceptionCode, String attemptedOperation, Boolean& closeStoreConnectionOnFailure)
   at System.Data.EntityClient.EntityConnection.Open()
   at System.Data.Objects.ObjectContext.EnsureConnection()
   at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
   at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator()
   at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
   at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2[TResult](IEnumerable`1 sequence)
   at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable`1 query, Expression queryRoot)
   at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
   at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
   at MyApp.Data.UserRepository.GetUserDetails(String username)
   at MyApp.Core.Services.SiteService.GetUserDetails(String username, Int64 userId)
   at MyApp.PublicSite.Web.Controllers.BaseController.Initialize(RequestContext requestContext)
   at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
   at MyApp.PublicSite.Web.Controllers.BaseController.Execute(RequestContext requestContext)
   at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
   at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
   at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
   at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
   at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
   at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

连接字符串为:

    <connectionStrings>
    <add name="MyAppDBContainer" connectionString="metadata=res://*/MyAppDB.csdl|res://*/MyAppDB.ssdl|res://*/MyAppDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=SERVERNAME;initial catalog=MyAppDB;persist security info=True;user id=USERID;Password=PASSWORD;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>

这个异常会随机发生,而且不是每次都能复现。我可能漏掉了哪些可能的设置?请给予建议。


当出现这个错误时,你的电脑是否在网络中?我认为你应该先检查你的局域网或互联网连接。 - Dharmik Bhandari
在本地环境中没有出现这个问题,我只在部署的服务器上遇到了这个异常。 - Prasad
@Prasad,请检查我提供的连接字符串。 - naim shaikh
你好。你能找到解决方法吗?我们也遇到了同样的问题,但是我们无法弄清原因。如果你能帮忙,我会非常感激。我们有时也会遇到这个错误,但不总是出现。 - Ada
4个回答

2

鉴于您所说的情况,它有时/大多数时候是有效的:

  • 连接字符串是正确的
  • SQL已正确配置(即允许远程连接等)

唯一可能的原因是您的服务器(您的代码)和SQL Server之间存在网络断开连接或SQL Server由于某种原因关闭。


当我从获取此异常的页面访问相同页面时,它可以正常工作,因此服务器关闭可能不是原因。网站和SQL服务器也在同一个服务器上,因此我不确定网络中断可能是原因。 - Prasad
搜索此错误会得到许多可能的解决方案。你解决了吗?另外,请特别运行 ping -t localhost(或你的SQL机器名称),让它运行一段时间,看看是否会不时丢失数据包。 - Ofer Zelig
我已经尝试了谷歌提供的所有选项,这些选项都已正确配置,但仍然出现异常:(。此外,我已经检查了ping,并且没有任何失败的回复。 - Prasad
谷歌搜索将我带到了这个页面!! - Homr Zodyssey

0

我们需要检查以下内容:

1.在SQL Server配置管理器设置中检查Tcp/IP设置。如果它被禁用了,请确保启用TCP/IP状态

2.在防火墙设置中添加端口例外。SQL端口的详细信息如下:

名称:SQL

端口号:1433

协议:选择TCP


0

为了允许远程连接,我们需要在SQL Server配置管理器中将属性设置为true for tcp/IP


-1

试试这个……

<add name="MyAppDBContainer" connectionString="metadata=res://*;provider=System.Data.SqlClient;provider connection string='data source=SERVERNAME;initial catalog=MyAppDB;persist security info=True;user id=USERID;Password=PASSWORD;multipleactiveresultsets=True;'" providerName="System.Data.EntityClient" />

我已经编辑了我的回答.....


它报错了:System.ArgumentException: 连接字符串中缺少一些必要的信息。'provider'关键字始终是必需的。 - Prasad
Naim,我已经将连接字符串更改为你更新的那个,但有时仍会出现连接错误。 - Prasad
是的,有时会失败。我能够在本地连接,甚至在服务器上部署它,但偶尔会抛出这个错误。 - Prasad
如果解释了正在更改的内容以及为什么会修复问题,那么这个答案将更好并且对其他人有用。 - thelem

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