存储过程InvalidCastException错误

时间:2014-11-14 17:50:23

标签: c#

我试图在一个简单的控制台应用程序中访问存储过程,出于某种原因,我得到了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 个答案:

答案 0 :(得分:3)

ADO.NET将nulls作为DBNull实例返回(非常奇怪,如果你问我的话)。因此,请使用以下检查读取值:

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

还要确保数字类型匹配,例如。你可能期望一个int,但你可能得到一个浮点数或一个小数。