2011-12-08 147 views
0

打開連接時,我收到了C#代碼中拋出的異常。 Visual Studio引發異常,說'連接未關閉。連接的當前狀態已打開。'。奇怪的是,連接根本沒有打開。爲什麼嘗試打開連接時會拋出異常?

奇怪的是,這個問題只發生在一臺PC(PC-1)上。在其他兩臺PC(PC-2和PC-3)上,代碼編譯並在其他兩臺PC上正常運行,沒有任何異常情況發生。如果我從這些PC-2或PC-3部署到Azure,則一切正常。

所有3臺PC都具有與VS2010相同版本的Visual Studio 2010 SP1(10.0.40219.1 SP1Rel),.NET(4.0.30319 SP1Rel),Azure 1.6 SDK,Azure Ap Fabric 1.5.37和Azure工具(1.6.41103.1601 )

下面的代碼的相關部分:

private long[] Foo(long rId, long mItemId) 
    { 
     List<long> list = null; 

     using (myDBEntities ctx = new myDBEntities()) 
     { 
      EntityConnection entityConnection = (EntityConnection)ctx.Connection; 

      using (DbConnection connection = entityConnection.StoreConnection) 
      { 
       connection.Open(); 
       ... 

以下是完整的異常詳細信息:

System.InvalidOperationException was unhandled by user code 
Message=The connection was not closed. The connection's current state is open. 
Source=System.Data 
StackTrace: 
    at System.Data.ProviderBase.DbConnectionInternal.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory) 
    at System.Data.SqlClient.SqlConnection.Open() 
    at myPost.Models.Repository.Foo(Int64 rId, Int64 mItemId) in C:\code\Models\Repository.cs:line 326 
    at myPost.Models.Repository.Foo(Int64 menuItemId, Int64 rId, mItemRatings[]& ratings, Photos[]& thumbnails) in C:\code\Models\Repository.cs:line 92 
    at myPost.Controllers.HomeController.Index(String part1, String part2, String embed) in C:\code\Controllers\HomeController.cs:line 97 
    at lambda_method(Closure , ControllerBase , Object[]) 
    at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) 
    at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) 
    at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) 
    at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() 
    at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) 
InnerException: 

在問題電腦(PC-1),以獲取代碼跑,我哈已在connection.Open();之前添加connection.Close();。但是,這在PC-2和PC-3上會出現問題,甚至更糟糕的是,當我部署到Azure時,我會拋出異常,因爲我添加的connection.Close()沒有必要。

我不知道PC-1上的設置有什麼問題,因爲它看起來像是配置問題,而不是代碼問題。

+0

在執行代碼之前,您是否從第一臺PC的SQL Server MS連接到Azure實例? – Lloyd

+0

不可以。Azure的唯一連接是來自此項目。這是我正在運行的唯一代碼。 – TMC

+0

您是否從VS數據庫嚮導創建了連接字符串,這也會導致相同的問題。如果您在本地構建和部署應用程序,而不僅僅是在VS內部,您是否也遇到同樣的問題? – Lloyd

回答

0

同意它可能不是一個代碼問題。只需在繼續之前對連接是打開還是關閉進行快速測試 - 無論如何可能最好這樣做。喜歡的東西:

if (connection.State == System.Data.ConnectionState.Open) 
{ 
    // ahoy, mate! 
} 
else 
{ 
    connection.Open(); 
    // here be dragons 
} 

我所有關於尋找在機器中的幽靈,但有時它做的狀態檢查,你的生活就只是更容易。

+0

我可以做到這一點,但我在這個過程中感到骯髒。我真的很想擺脫「幽靈」! – TMC

相關問題