.net EF Core 6 -在dbContext中创建关系时出错

kt06eoxx  于 2023-03-04  发布在  .NET
关注(0)|答案(2)|浏览(156)

下面是创建this Relation所需的关系
下面是每个表的实体类
机场表格:

[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>();
    }
}

航班时刻表:

[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>();
    }
}

下面是我在OnModelCreating()方法中对DbContext的配置:

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

从SQL服务器构建的图表看起来像我设计的,但是当我为这两个表添加一些数据种子时,只有Airport工作,Flight Schedule将产生此错误
未按约定配置从“Airport”到“FlightSchedule”的关系,因为一个实体类型({“ArrivalAirports”,“DepartureAirports”})上有多个属性可以与其他实体类型({“AirportArrival”,“AirportDeparts”})上的属性匹配。如果已在“OnModelCreating”中指定显式配置,则可以忽略此消息。
我怀疑我的配置可能是错误的,但我不确定原因是什么,因为这是我第一次尝试先使用代码。

e0bqpujr

e0bqpujr1#

我认为您在DbContext中遗漏了下一个代码:

modelBuilder.Entity<Airport>()
.HasMany(a => a.DepartureAirports)
.WithOne(fs => fs.AirportDepart)
.HasForeignKey(fs => fs.DepartureAirportId);

modelBuilder.Entity<Airport>()
    .HasMany(a => a.ArrivalAirports)
    .WithOne(fs => fs.AirportArrival)
    .HasForeignKey(fs => fs.ArrivalAirportId);

这是因为您没有设置从Airport到FlightSchedule的关系

zpqajqem

zpqajqem2#

在表FlightSchedule中,列DepartureAirportIdArrivalAirportId需要设置为可空
FlightSchedule表中的记录只能具有其中一个值,不能同时具有这两个值。

相关问题