I have a Station entity (in the context of bus stations). This Station entity has a collection of Stations to represent the destinations. How can I map that as a many-to-many relationship in EF Core?
public class Station {
[Key]
public int StationId { get; set; }
[Required]
[Column(TypeName = "VARCHAR")]
[StringLength(100)]
public string TerminalName { get; set; }
[Required]
[Column(TypeName = "VARCHAR")]
[StringLength(100)]
public string City { get; set; }
[Required]
[Column(TypeName = "VARCHAR")]
[StringLength(100)]
public string Province { get; set; }
public ICollection<Station> Destinations { get; set; }
}
I’m having trouble doing it and upon running a migration for this, it produces this error:
The navigation 'Station.Destinations' cannot be used for both sides of a many-to-many relationship. Many-to-many relationships must use two distinct navigation properties.
2
Answers
We can’t really model undirected graphs in a first-class way. The linking table has to have a FromStation,ToStation, and if you can always go both ways, you need two entries. So try something like
First you need this additional class
Next add two lists in your station class
Then create a mapping folder and add class in this folder and use
IEntityTypeConfiguration
Finally configure your
Db