簡體   English   中英

嘗試打開連接時為什么會引發異常?

[英]Why is an exception thrown when trying to open a connection?

打開連接時,我的C#代碼中引發了異常。 Visual Studio引發異常,指出“連接未關閉。 連接的當前狀態為打開。 奇怪的是,連接根本沒有打開。

奇怪的是,該問題僅在一台PC(PC-1)上發生。 在其他2台PC(PC-2和PC-3)上,代碼可以編譯並在這2台其他PC上正常運行,不會引發任何異常。 如果我從這些PC-2或PC-3部署到Azure,則一切正常。

所有3台PC均具有相同版本的Visual Studio 2010 SP1(10.0.40219.1 SP1Rel)、. NET(4.0.30319 SP1Rel),Azure 1.6 SDK,Azure Ap Fabric 1.5.37和適用於VS2010的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(PC-1)上,為了運行代碼,我必須添加一個connection.Close(); 就在connection.Open(); 但是,這會在PC-2和PC-3上中斷,甚至更糟,當我部署到Azure時,會拋出異常,因為我添加的connection.Close()不必要。

我不知道PC-1上的安裝有什么問題,因為這似乎是配置問題,而不是代碼問題。

同意這可能不是代碼問題。 在繼續操作之前,只需對連接是打開還是關閉進行快速測試-可能最好還是這樣做。 就像是:

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

我只是想在機器中找到Ghost,但是有時候狀態檢查和繼續生活更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM