我有一个要实现的数据库设计,这很困难,并出现错误“有多个ForeignKeyAttributes指向同一组属性”
我们有一个飞机场和一个航班,一个航班有一个要飞往其所在的机场的外键,还有另一个要飞往该航班的机场的外键。
,但是两个机场都在同一张表中。 Flight表中有两个外键指向Airport表中的同一列
机场舱
{
public class Airport
{
[Key]
public int Id { get; set; }
[ForeignKey(nameof(Flight.ToAirportId))]
public ICollection<Flight> ComingFlightsId { get; set; }
[ForeignKey(nameof(Flight.FromAirportId))]
public ICollection<Flight> GoingFlightsId { get; set; }
}}
航班舱位
{
public class Flight
{
[Key]
public int Id { get; set; }
[ForeignKey(nameof(FromAirportId))]
public Airport FromAirport { get; set; }
public int FromAirportId { get; set; }
[ForeignKey(nameof(ToAirportId))]
public Airport ToAirport { get; set; }
public int ToAirportId { get; set; }
}}
答案 0 :(得分:2)
只需使用此:
public class Airport
{
public int Id { get; set; }
[InverseProperty("FromAirport")]
public ICollection<Flight> ComingFlights { get; set; }
[InverseProperty("ToAirport")]
public ICollection<Flight> GoingFlights { get; set; }
}
public class Flight
{
public int Id { get; set; }
public int FromAirportId { get; set; }
public int ToAirportId { get; set; }
[ForeignKey(nameof(FromAirportId))]
[InverseProperty("ComingFlights")]
public Airport FromAirport { get; set; }
[ForeignKey(nameof(ToAirportId))]
[InverseProperty("GoingFlights")]
public Airport ToAirport { get; set; }
}
答案 1 :(得分:1)
我找到了问题的答案。 Inverse Property
将此注释添加到ICollection
在我的情况下,这是机场班级的样子
{
public class Airport
{
[Key]
public int Id { get; set; }
public string Locatoin { get; set; }
[InverseProperty(nameof(Flight.ToAirportId))]
public ICollection<Flight> ComingFlightsId { get; set; }
[InverseProperty(nameof(Flight.FromAirportId))]
public ICollection<Flight> GoingFlightsId { get; set; }
}}
答案 2 :(得分:0)
尝试在virtual
和public ICollection<Flight> ComingFlightsId { get; set; }
上使用public ICollection<Flight> GoingFlightsId { get; set; }
修饰符,并从其中删除ForeignKey
属性