2014-11-14 119 views
0

我試圖訪問一個簡單的控制檯應用程序中的存儲過程,出於某種原因,我得到一個InvalidCastException存儲過程InvalidCastException錯誤

任何人都可以幫忙嗎?

class Customer 
    { 
     public int CustomerID { get; set; } 
     public string FirstName { get; set; } 
     public string SecondName { get; set; } 
     public int Age { get; set; } 
    } 

    static void Main(string[] args) 
    { 
     string storedProc = "dogssimple"; 
     List<Customer> custList = new List<Customer>(); 

     SqlConnection conn = new SqlConnection("server=localhost;" + 
            "Trusted_Connection=yes;" + 
            "database=mydatabase; " + 
            "connection timeout=30"); 
     try 
     { 
      conn.Open(); 

      SqlCommand cmd = new SqlCommand(storedProc, conn); 

      cmd.CommandType = CommandType.StoredProcedure; 

      SqlDataReader rdr = cmd.ExecuteReader(); 

      while (rdr.Read()) 
      { 
       Customer addCustomer = new Customer() //..... cast exception here 
       { 
        CustomerID = (int)rdr["CustomerID"], 
        FirstName = (string)rdr["FirstName"], 
        SecondName = (string)rdr["SecondName"], 
        Age = (int)rdr["Age"], 
       }; //.... 

       Console.WriteLine("Customer: {0}, {1}, {2}, {3}", addCustomer.CustomerID, addCustomer.FirstName, addCustomer.Age, addCustomer.Age); 
       custList.Add(addCustomer); 
      } 

      var age = from x in custList 
         select x.Age; 
      var avgAge = age.Average(); 

      Console.WriteLine("The average age of the customers is " + avgAge); 
     } 
     catch (Exception e) 
     { 
      Console.WriteLine(e); ; 
     } 

     Console.ReadLine(); 
} 
+1

包含整個堆棧跟蹤。快速猜測會從存儲過程返回的類型與您正在投射的內容不匹配。 – AlG 2014-11-14 17:52:08

回答

3

ADO.NET將NULL作爲DBNull實例返回(非常奇怪,如果你問我)。因此,請閱讀以下檢查值:

SecondName = rdr["SecondName"] is DBNull ? null : (string)rdr["SecondName"] 

還要確保數字類型匹配,例如。你可能會期望一個int,但你可能會得到一個浮點數或小數點。

+1

這裏是一個[問題](http://stackoverflow.com/questions/4958379/what-is-the-difference-between-null-and-system-dbnull-value)與答案,觸及爲什麼DBNull存在 – juharr 2014-11-14 18:04:01

+0

謝謝@ fejesoco用你的答案追溯了這個問題。將從現在開始應用。 – 2014-11-14 18:11:59