2013-04-24 37 views
0

我有一個簡單的應用程序,它從數據庫讀取以設置類中的屬性,然後將結果集輸出到屏幕以及寫入文件。我試圖提前計劃我的應用程序成爲一個Web應用程序,並希望它儘可能地被設計成儘可能最佳的實踐。我想知道我的DAL設計是否存在重大缺陷,以及如果我從用戶那裏接受輸入並將其設置爲參數的方式是正常的,或者有更好的方法來實現它。程序中的所有內容都按預期工作。在數據訪問層中使用存儲過程

DAL

public static List<Customers> GetCustomersByName() 
     { 
      //make the list of the type that the method will be returning 
      List<Customers> c = new List<Customers>(); 
      //make a connection string variable 
      string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(cs)) 
      { 
       using(SqlCommand cmd = new SqlCommand("spFindCustomersByName",con)) 
       { 
        con.Open(); 
        //this stored procedure has one input parameter, how do I send that to the data access layer? 
        cmd.CommandType = CommandType.StoredProcedure; 
        cmd.Parameters.Add("@lastName", SqlDbType.VarChar, 50); 
        //only way I could think of to get the value entered from a screen into 
        //a parameter 
        cmd.Parameters["@lastName"].Value = Customers.AddSpParams(); 

        //instantiate SqlDataReader 
        SqlDataReader rdr = cmd.ExecuteReader(); 
        while(rdr.Read()) 
        { 
         Customers custList = new Customers(); 
         custList.CustomerId = Convert.ToInt32(rdr["customerId"]); 
         custList.LastName = rdr["lastName"].ToString(); 
         custList.FirstName = rdr["firstName"].ToString(); 
         custList.DateHired = (DateTime)rdr["dateHired"]; 
         c.Add(custList); 



        } 

       } 
       return c; 
      } 

法值分配給該存儲的過程

public static string AddSpParams() 
     { 
      Console.Write("Search for a string in customer's name: "); 
      string nameParam = Console.ReadLine(); 
      return nameParam; 
     } 

寫入文本文件的輸入參數,寫入到控制檯

static void Main(string[] args) 
     { 
      Console.WriteLine("This is only a test"); 
      List<Customers> c = DataAccessCustomers.GetCustomersByName(); 
      using (StreamWriter sw = new StreamWriter(@"C:\Users\customersList.txt")) 
      { 
       foreach(Customers custList in c) 
       { 
        //write to console 
        Console.WriteLine(custList.CustomerId + "\t" + custList.FirstName + "\t" + 
         custList.LastName + "\t" + custList.DateHired); 
        //write to file 
        sw.WriteLine(custList.CustomerId + "\t" + custList.FirstName + "\t" + 
         custList.LastName + "\t" + custList.DateHired); 
       } 
      } 
      Console.ReadLine(); 
     } 
+0

這需要轉移到代碼審查。 – 2013-04-24 13:46:56

+0

我不知道存在。我會怎麼做? – wootscootinboogie 2013-04-24 13:49:34

+2

你可以在這裏找到:http://codereview.stackexchange.com/ – 2013-04-24 14:07:00

回答

2

基本上,有你的設計異常小點在這裏沒有問題。我假設你的商店程序和Customer類不支持空值。所以,在這裏主要的主要缺陷是你的代碼仍然不能處理的DBNull值:

custList.LastName = rdr["lastName"].ToString(); 
custList.FirstName = rdr["firstName"].ToString(); 
custList.DateHired = (DateTime)rdr["dateHired"]; 

你應該之前調用.ToString()或拳擊(DateTime)rdr["dateHired"]; 檢查RDR [「姓氏」]和RDR [「名字」]的DBNull的價值希望這個幫助。