0

Error:

Constraint "FK_DestinationsLists_Regions_AirportCode" of relation "DestinationsLists" does not exist

I am working an ASP.NET Core project. I faced this issue while updating database after add a new migration.

I have three tables:

  1. DestinationsList
  2. Regions
  3. Flights

Now I want to add a FK for Flights; DestinationsList and Flights have a one-to-many relationship. For Flight table, ArrivalAirportCode is the foreign key column.

I try to add foreign key for ArrivalAirportCode from DestinationsList table. But EF took FK from Regions. Why?

public class DestinationsList
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)
    public int Id { get; private set; }
    public string AirportCode { get; private set; }
    public Region Region { get; set; }
    public IEnumerable<Flight> Flights { get; set; }
}

public class Region
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string AirportCode { get; set; }
    public string AirportShortCode { get; set; }
    public DestinationsList DestinationsLists { get; set; }
}

public class Flight
{
    public int Id { get; set; }
    [Required]
    public string ArrivalAirportCode { get; set; }
    public DestinationsList ArrivalAirport { get; set; }
}

DbContext:

public DbSet<DestinationsList> DestinationsLists { get; set; }
public DbSet<Region> Regions { get; set; }
public DbSet<Flight> Flight { get; set; }

builder.Entity<DestinationsList>()
                .HasOne(i => i.Region)
                .WithOne(i => i.DestinationsLists)
                .HasPrincipalKey<Region>(i => i.AirportShortCode)
                .HasForeignKey<DestinationsList>(i => i.AirportCode);   // This is already there

builder.Entity<Flight>()
                .HasOne(x => x.ArrivalAirport)
                .WithMany(x => x.Flights)
                .HasForeignKey(x => x.ArrivalAirportCode)
                .HasPrincipalKey(x => x.AirportCode);             // This one I tried newly for add FK to Flights
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
hanushic
  • 369
  • 1
  • 5
  • 19
  • AirportCode is not a valid foreign key, they foreign key should the primary from the related table (ID) – Vince Oct 27 '21 at 06:52
  • Foreign key should be unique from related table. Is it? no need to should be a primary key? Am not right? – hanushic Oct 27 '21 at 07:13
  • Based on you code AirportShortCode is NOT a key. edit: see this https://stackoverflow.com/questions/18435065/foreign-key-to-non-primary-key – Vince Oct 27 '21 at 07:19

0 Answers0