Here is the relationship I need to create this Relation
And here are the entity classes for each table
The Airport table:
[Table("Airport")]
public class Airport
{
[Key]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string City { get; set; }
[Required]
[MaxLength(50)]
public string Country { get; set; }
public ICollection<FlightSchedule> DepartureAirports { get; set; }
public ICollection<FlightSchedule> ArrivalAirports { get; set; }
public Airport()
{
DepartureAirports = new List<FlightSchedule>();
ArrivalAirports = new List<FlightSchedule>();
}
}
The Flight Schedule table:
[Table("FlightSchedule")]
public class FlightSchedule
{
[Key]
public Guid Id { get; set; }
[Required]
public Guid DepartureAirportId { get; set; }
public Airport AirportDepart { get; set; }
[Required]
public Guid ArrivalAirportId { get; set; }
public Airport AirportArrival { get; set; }
[Required]
public DateTime DepartureTime { get; set; }
[Required]
public DateTime ArrivalTime { get; set; }
public ICollection<Flight> Flights { get; set; }
public FlightSchedule()
{
Flights = new List<Flight>();
}
}
And here is my config for DbContext in OnModelCreating() method:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Airport>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedOnAdd();
});
modelBuilder.Entity<FlightSchedule>(entity =>
{
entity.Property(e => e.Id).ValueGeneratedOnAdd();
entity.HasOne(e => e.AirportDepart)
.WithMany(e => e.DepartureAirports)
.HasForeignKey(e => e.DepartureAirportId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(e => e.AirportArrival)
.WithMany(e => e.ArrivalAirports)
.HasForeignKey(e => e.ArrivalAirportId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
The diagram built from SQL server looks like what I designed but when I add some data seeder for those 2 tables, only Airport works, Flight Schedule would produce this error
No relationship from 'Airport' to 'FlightSchedule' has been configured by convention because there are multiple properties on one entity type - {'ArrivalAirports', 'DepartureAirports'} that could be matched with the properties on the other entity types - {'AirportArrival', 'AirportDepart'}. This message can be disregarded if explicit configuration has been specified in 'OnModelCreating'.
I suspect maybe my configuration is wrong but I'm not sure where the cause is, since this is my first time trying with code first.
In your table FlightSchedule
, columns DepartureAirportId
and ArrivalAirportId
need to be set up at nullable.
A record in FlightSchedule
table can have only one of these values, not both.