2014-05-14 43 views
0

FBConnection的使用給了我一些麻煩。 在Firebird Ole-Db的示例中,我只找到了使用靜態主方法的示例,但我不確定如何在實例方法中實現FbConnection的使用。Firebird FBConnection失去連接String

現在我正在初始化並使用下面的代碼示例中所示的連接。 每隔一段時間我都會收到錯誤「connectionstring未初始化」。連接對象不爲null,但連接字符串似乎爲空。 是什麼導致了這種行爲?我應該每次訪問該方法時重新初始化FbConnect對象(使其成爲局部變量),還是這種性能方式是一個非常糟糕的主意?

public class MyUserStore<TUser> : IUserPasswordStore<TUser, int>, IUserStore<TUser, int>, IDisposable where TUser : ApplicationUser, new() 
        { 
       private FbConnection Connection = new FbConnection("User=-----;" + 
               "Password=-------;" + 
                "Database=C:\\------\\Testing.GDB;" + 
                "DataSource=localhost;" + 
                "Dialect=3;Charset=NONE;"); 
      public Task<TUser> FindByIdAsync(int userId) 
        { 
         if (userId == 0) 
         { 
          throw new ArgumentNullException("userId"); 
         } 
         TUser User = null; 

         if (Connection != null) 
         { 
          FbTransaction transaction = null;  
          FbDataReader Reader = null; 
          using (Connection) 
          { 
           try 
           { 
            Connection.Open(); 

            FbCommand Command = new FbCommand(GetByIdQuery, Connection); 
            Command.Parameters.AddWithValue("id", userId); 
            Reader = Command.ExecuteReader(); 
           catch (Exception e) 
           { 
            if (transaction != null) 
            { 
            transaction.Rollback(); 
            } 
            System.Diagnostics.Debug.WriteLine(e.StackTrace); 
            return Task.FromResult<TUser>(null); 
           } 
           finally 
           { 
           if (Reader != null) 
           { 
            Reader.Close(); 
           } 
           Connection.Close(); 
           } 
         } 
        } 
     } 
+0

我不認爲你應該在實例字段中存儲連接,如果你打算在'using()'-block中使用它。在「使用」本身中創建連接。 –

回答

0

Mark Rotteveel在他的評論中是正確的。 顯然,使用條款意味着資源在塊的末尾處理正確。這意味着我需要每次使用「使用」塊時創建一個新連接。