concept Flight in category c#

appears as: Flight
Code like a Pro in C#

This is an excerpt from Manning's book Code like a Pro in C#.

Looking at figure 3.9, the Flight and Booking tables are the only entities with foreign key relationships (two each). In the Flight table, Flight.Origin ties to Airport.AirportID, and so does Flight.Destination. In the Booking table, Booking.FlightNumber ties to Flight.FlightNumber, and Booking.CustomerID ties to Customer.CustomerID. Then, finally, there are the Airport and Customer tables, who have no outgoing foreign key relationships (they both have one incoming foreign key relationship). All four tables in the schema have a Primary Key, as denoted by the upright key icon.

When considering the hard-coded connection string in section 4.1.3, what went through your mind? Did you see any problems with this? If so, what were they? The problem is not with the actual content of the connection string. The connection details are correct and we want to have a list holding objects of type Flight. The problem is that we have a hard-coded connection string in our controller.

The reader allows us to parse the database response into a more manageable form. We can see this in action if we step inside the using statement, where we create a new Flight object. The Flight object takes in three parameters, all 32-bit integers (int): flightNumber, originID, destinationID. These also are the columns of our Flight table (if we take into account the slight misnaming we discussed earlier in this chapter). We know the order the columns are returned in, because we know the database schema. It probably would have been cleaner to specify what columns the query should return. If we explicitly say what columns we want to be returned, we can control the data flow better and know exactly what we are going to get. It does not require a developer unfamiliar with the code or database schema to do more research to find out what the expected returns are.

The code in listing 4.2 calls the reader’s GetInt32 method and pass in the value's index we are looking for. Once the Flight object is created, it is added to the flights collection. Moving on, take a minute to look over the code in listing 4.3. Hopefully, you see some very familiar things.

Listing 4.3 FlightController.cs GET Flight: getting the Origin Airport details
// Get Origin Airport details
cmd = new SqlCommand("SELECT City FROM Airport WHERE AirportID = " + ➥flight.OriginID, connection); #A
 
using (var reader = cmd.ExecuteReader()) #B
{
    while (reader.Read()) #C
    {
        returnView.Origin = reader.GetString(0); #D
        break;
    }
}
 
cmd.Dispose();
 
flightReturnViews.Add(returnView);