2014-05-14 42 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在他的评论中是正确的。 显然,使用条款意味着资源在块的末尾处理正确。这意味着我需要每次使用“使用”块时创建一个新连接。