简体   繁体   中英

Seeding database with a one-to-many relationship in ASP.NET MVC using Entity Framework

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

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.

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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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