0

I was trying out accessing stored procedures in a simple console app and for some reason I get a 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();   
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
G Gr
  • 6,030
  • 20
  • 91
  • 184
  • 1
    Include the entire stack trace. Quick guess would be the type coming back from the stored procedure doesn't match what you are casting to. – AlG Nov 14 '14 at 17:52

1 Answers1

3

ADO.NET returns nulls as a DBNull instance (very weird, if you ask me). 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.

fejesjoco
  • 11,763
  • 3
  • 35
  • 65
  • 1
    Here's a [question](http://stackoverflow.com/questions/4958379/what-is-the-difference-between-null-and-system-dbnull-value) with answers that touches on why DBNull exisits – juharr Nov 14 '14 at 18:04
  • Thanks @fejesoco traced the problem with your answer. Will apply this from now on. – G Gr Nov 14 '14 at 18:11