2010-11-30 45 views
0

我有一段時間沒有使用SqlCommand等訪問數據,因爲我傾向於現在使用NHibernate。我只是想知道下面的代碼是否可以改進。我嘗試過使用最佳做法(在谷歌搜索之後),並在更高層捕獲潛在的例外情況。最簡潔的方式來訪問asp.net中的sproc數據

[WebMethod] 
    public XmlDocument GetClassRegistrationReport() 
    { 
     XmlDocument doc = new XmlDocument(); 

     using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["bla"].ToString())) 
     { 
      using (SqlCommand command = connection.CreateCommand()) 
      { 
       command.CommandText = "bla"; 
       command.CommandType = CommandType.StoredProcedure; 
       connection.Open(); 
       doc.Load(command.ExecuteXmlReader()); 
      } 
     } 

     return doc; 
    } 

Thanks! 

最良好的祝願,

基督教

回答

2

有你可以改善它一點幾種方法:

  • 雖然將WebMethod提取數據,然後返回逐字沒有輸入參數,我會建議將服務接口和數據分成獨立的類。這可能會讓事情在以後更容易維護。
  • 假設您的框架中還有其他數據庫調用,您可能需要考慮數據層中的輔助方法,它包裝存儲過程的調用。這樣,您只有一種方法可以將所有SP調用過濾掉,以便將來再次維護時更容易。
  • 爲連接字符串設置「bla」鍵以設置常量,這樣您可以輕鬆地重新使用和更改。
  • 這同樣適用於存儲過程的名稱,或者將其作爲web.config的一部分 - 這意味着您可以在不必重新編譯的情況下更改存儲的proc名稱。
  • 如果發生異常,則不會進行處理,因此異常會向調用方冒泡,請考慮捕獲並處理/記錄異常。也就是說你確實提到你正在處理更高層的異常,所以我認爲這是在任何調用你的web服務的過程中完成的。
  • 你應該配置的SQL命令對象(在最後的try/catch /最後,如果你做執行異常處理的)

編輯:代碼示例

public class MyWebService 
{ 
    [WebMethod] 
    public XmlDocument GetClassRegistrationReport() 
    { 
     return DataLayer.GetClassRegistrationReport(); 
    } 
} 
// Notice that this is a static internal class, internal to hide the 
// data access class from everything but this library and static because 
// we don't need instances and using statics will optimise a little. 
internal static class DataLayer 
{ 
    private const string SP_GetRegistrationReport = "GetRegistrationReport"; 
    private const string Config_DBConnectionString = "PrimaryDB"; 

    private static string GetDB 
    { 
     get 
     { 
      string dbConnectionString = ConfigurationManager.ConnectionStrings[Config_DBConnectionString].ConnectionString; 

      if (string.IsNullOrEmpty(dbConnectionString)) 
      { 
       // This error should could/should be in a resource file. 
       throw new ConfigurationException("Database connection string is not defined"); 
      } 

      return dbConnectionString; 
     } 
    } 

    internal static XmlDocument GetClassRegistrationReport() 
    { 
     XmlDocument doc = new XmlDocument(); 

     using (SqlConnection connection = new SqlConnection()) 
     { 
      using (SqlCommand command = connection.CreateCommand()) 
      { 
       command.CommandText = SP_GetRegistrationReport; 
       command.CommandType = CommandType.StoredProcedure; 
       connection.Open(); 
       doc.Load(command.ExecuteXmlReader()); 
      } 
     } 

     return doc; 
    } 
} 
+0

我已經更新了一些東西(將sql命令對象包裝成using語句)。這應該照顧在異常情況下的cloasing/disposing不應該嗎? ConfigurationManager.ConnectionStrings [「bla」]是否不訪問web.config中的「全局變量」?你能否添加一些鏈接給你的建議?謝謝! – cs0815 2010-11-30 12:07:51

相關問題