![](/img/trans.png)
[英]How to create a table with two foreign keys pointing to the same table using Entity Framework Code First
[英]How to Create two Foreign Keys in one Table pointing to the same Column in some table?
我有一个我要实现的数据库设计,这很困难,并出现错误“有多个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; }
}}
只需使用这个:
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; }
}
我找到了问题的答案。 逆属性
将此注释添加到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; }
}}
尝试在public ICollection<Flight> ComingFlightsId { get; set; }
上使用virtual
修饰符public ICollection<Flight> ComingFlightsId { get; set; }
public ICollection<Flight> ComingFlightsId { get; set; }
public ICollection<Flight> ComingFlightsId { get; set; }
和public ICollection<Flight> GoingFlightsId { get; set; }
public ICollection<Flight> GoingFlightsId { get; set; }
public ICollection<Flight> GoingFlightsId { get; set; }
然后从其中删除ForeignKey
属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.