I'm having issues with the SQL reader class.
I have a custom object named Airport on the database. But im having trouble using the datareader correctly. When i try to extract all Airports into a list(see method 2 below) it seems to jump of the while(_reader.Read()) loop before adding the object to the list.
Any suggestions?
To extract the object do i use 3 methods:
To find a specific object:
public Airport FindAirportByCode(string _airportCode) { con.Open(); string query = "SELECT * from Airport WHERE airportCode = '" + _airportCode + "'"; SqlCommand cmd = new SqlCommand(query, con); SqlDataReader _reader = cmd.ExecuteReader(); Airport retAirport = BuildAirport(_reader); _reader.Close(); con.Close(); return retAirport; }To get all Airports into a list
public List<Airport> SelectAll() { con.Open(); List<Airport> airports = new List<Airport>(); string query = "SELECT * from Airport"; SqlCommand cmd = new SqlCommand(query, con); SqlDataReader _reader = cmd.ExecuteReader(); while (_reader.Read()) { Airport temAirport = new Airport(); temAirport = BuildAirport(_reader); airports.Add(temAirport); // It seems to skip this step and only add the last Airport from BuildAirport to the list. } _reader.Close(); con.Close(); return airports; }To build it into an object in C#
private Airport BuildAirport(SqlDataReader _reader) { Airport temAirport = new Airport(); while (_reader.Read()) { temAirport.airportCode = (string) _reader["airportCode"]; temAirport.airportName = (string) _reader["airportName"]; temAirport.country = (string) _reader["country"]; temAirport.city = (string) _reader["city"]; } _reader.Close(); return temAirport; }