0

I have problems defining an entity with my models.

My models are:

public class Airport
{
    [Key]
    public int AirportId {get; set;}
    public string Name {get; set;}
    public string Address {get; set;}
    public List<Flight> DepartingFlights {get; set;}
    public List<Flight> ArrivingFlights {get; set;}
}

public class Flight
{
    [Key]
    public int FlightId {get; set;}
    public int Distance {get; set;}
    public float Duration {get; set;}
    public Airport DepartureAirport {get;set;}
    public Airport ArrivalAirport {get;set}
}

I have also tried to add entities in dbContext like this:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Flight>()
                .HasOne(f => f.DepartureAirport)
                .WithMany(a => a.DepartingFlights);

    modelBuilder.Entity<Flight>()
                .HasOne(f => f.ArrivalAirport)
                .WithMany(a => a.ArrivingFlights);

    modelBuilder.Entity<Airport>()
                .HasMany(a => a.DeparturingFlights)
                .WithOne(f => f.DepartureAirport);

    modelBuilder.Entity<Airport>()
                .HasMany(a => a.ArrivingFlights)
                .WithOne(j => j.ArrivalAirport);

    base.OnModelCreating(modelBuilder);
}

With this approach I get an error:

Cannot create, drop, enable, or disable more than one constraint, column, index, or trigger named 'FK_flights_airports_DepartureAirportId' in this context. Duplicate names are not allowed.
Column names in each table must be unique. Column name 'DepartureAirportId' in table 'flights' is specified more than once.

How could this problem be solved?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
bunkki
  • 1
  • Refer to this similar [issue](https://stackoverflow.com/questions/35476618/ef-code-first-one-to-many-twice-to-same-collection-type), it only needs to config once. – Xinran Shen Dec 20 '22 at 01:37

1 Answers1

0

You only need to define the one-to-many relationship once,

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
      modelBuilder.Entity<Flight>()
                .HasOne(f => f.DepartureAirport)
                .WithMany(a => a.DepartingFlights);
      modelBuilder.Entity<Flight>()
                .HasOne(f => f.ArrivalAirport)
                .WithMany(a => a.ArrivingFlights);
      base.OnModelCreating(modelBuilder);
}

Charles Han
  • 1,920
  • 2
  • 10
  • 19