2014-11-14 123 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