简体   繁体   English

存储过程InvalidCastException错误

[英]Stored procedure InvalidCastException error

I was trying out accessing stored procedures in a simple console app and for some reason I get a InvalidCastException . 我试图在一个简单的控制台应用程序中访问存储过程,由于某种原因,我收到了InvalidCastException

Can anyone help? 有人可以帮忙吗?

    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();   
}

ADO.NET returns nulls as a DBNull instance (very weird, if you ask me). ADO.NET返回空值作为DBNull实例(如果您问我,这很奇怪)。 So read values with the following check: 因此,请通过以下检查来读取值:

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

Also make sure that numeric types match, eg. 还要确保数字类型匹配,例如。 you may expect an int but you may get a float or a decimal. 您可能需要一个整数,但可能会得到一个浮点数或一个十进制数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM