I have a database design I want to implement, which is hard and make the error "there were multiple ForeignKeyAttributes which are pointing to same set of propertie"
we have an airport and flights, a flight have a Foreign key to the airport that it's flying from, and another Foreign key to the airport the flight is going to.
but both airports are in the same table. there for the Flight table has two foreign key pointing at the same column in the Airport table
the Airport Class
{
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; }
}}
the flight class
{
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; }
}}
Just use this :
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; }
}
I found an answer to my question. Inverse Property
add this annotation to the ICollection
this how the Airport class should look like in my case
{
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; }
}}
Try to use virtual
modifier on public ICollection<Flight> ComingFlightsId { get; set; }
public ICollection<Flight> ComingFlightsId { get; set; }
public ICollection<Flight> ComingFlightsId { get; set; }
and public ICollection<Flight> GoingFlightsId { get; set; }
public ICollection<Flight> GoingFlightsId { get; set; }
public ICollection<Flight> GoingFlightsId { get; set; }
and remove ForeignKey
attribute from them
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.