2013-04-07 200 views
0

我有一個模型中的以下代碼用於處理所有與數據庫相關的活動,所以我不會在每次我想要編寫冗餘代碼段時與數據庫的工作,這個模型類是這樣的:ConnectionString屬性尚未初始化,但訪問靜態屬性

Shared.cs

private static string ConStr 
    { 
     get 
     { 
      Shared shrObj = new Shared(); 
      return shrObj.DecryptString(ConfigurationManager.ConnectionStrings["constr"].ConnectionString); 
     } 

    } 

    public static SqlConnection SqlCon = new SqlConnection(ConStr); 

    public static SqlDataReader ORC(SqlCommand sqlCom) 
    { 
     SqlDataReader sqlReader=null; 

     try 
     { 
      SqlCon.Open();//ERROR HERE 
      //The ConnectionString property has not been initialized. 
      sqlReader = sqlCom.ExecuteReader(); 

     } 
     catch (Exception ex) 
     { 
      WriteToFile(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss") + " | " + ex, 0); 
      return sqlReader; 
     } 
     return sqlReader; 
    } 
      //Functions for closing connections… 
      //Functions for reading scalar… 
      //etc. 

而且現在從其他車型,當我嘗試使用這些功能是這樣的: User.cs

internal IEnumerable<User> GetUser() 
    { 
     var sqlCom = new SqlCommand("SELECT * FROM [user];", Shared.SqlCon); 

     using (var blgs = Shared.ORC(sqlCom)) 
     { 
      // ……. … … 
      } 
     } 
    } 

還有一件讓我困惑的事情是,當這個數據讀取功能在這裏第一次從這裏登錄時被調用,它工作正常,它總是第二次調用這會產生問題。

可能是我只是不玩靜態屬性寫。但我必須保持靜態,因爲它本身是靜態的,可以直接從課堂外直接使用,因爲它被SqlConnection對象使用。

請幫忙。

回答

0

在一個web應用程序,它通常是更好地打開和關閉通過using語句,像這樣的連接:

using (SqlConnection conn = new SqlConnection(connectionString)) 
    { 
    conn.Open(); 
// do some stuff 
} 

不要重複使用的SqlConnection,因爲它會導致你的webapp意外超時。

相關問題