skip to Main Content

Struggling to properly seed my database when my app starts up. FlightId, DepartureAirportId, ArrivalAirportId, FlightDateTime and FlightDurationHours all get added but how can I ensure the Airport column is added.

I have set-up a one to many relationship with Entity Framework between Airport and Flights.

The below code is inside my AddDbInitializer class which runs at start-up.

new Flight()
{
    DepartureAirportId = 3,
    ArrivalAirportId = 7,
    FlightDateTime = new DateTime(2021, 12, 21, 08, 0, 0, 0),
    FlightDurationHours = 2,
    Airport = context.Airports.Find(3) // ADDED THIS LINE BUT IT DOESN'T WORK
}

Flight class:

public class Flight
{
    public int FlightId { get; set; }
    public int DepartureAirportId { get; set; }
    public int ArrivalAirportId { get; set; }
    public DateTime FlightDateTime { get; set; }
    public int FlightDurationHours { get; set; }
    public Airport Airport { get; set; }
}

Airport class:

public class Airport
{
    public int AirportId { get; set; }
    public string AirportCode { get; set; }

    public ICollection<Flight> Flight { get; set; }
}

2

Answers


  1. Did you context.SaveChanges() after saving the airport?

    You can add the data, but if you want to reference it for adding additional items, you need to commit it first otherwise it technically isn’t there yet.

    Login or Signup to reply.
  2. Airport= context.Airports.Find(3) would be null That is not the correct way to use find method from LINQ. One way would be using lambda expression, change by context.Airports.find(x=>x.AirportId==3) Or you could the whole as a LINQ expression:
    var airport=select a from context.Airports where a.AirportId==3;
    new Filght(){
    ….
    Aiport=airport
    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search