下面是创建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”中指定显式配置,则可以忽略此消息。
我怀疑我的配置可能是错误的,但我不确定原因是什么,因为这是我第一次尝试先使用代码。
2条答案
按热度按时间e0bqpujr1#
我认为您在DbContext中遗漏了下一个代码:
这是因为您没有设置从Airport到FlightSchedule的关系
zpqajqem2#
在表
FlightSchedule
中,列DepartureAirportId
和ArrivalAirportId
需要设置为可空。FlightSchedule
表中的记录只能具有其中一个值,不能同时具有这两个值。