这应该做你需要的......
public class Airport
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Route> DepartureRoutes { get; set; }
public virtual ICollection<Route> DestinationRoutes { get; set; }
}
public class Route
{
public int DepartureAirportID { get; set; }
public int DestinationAirportID { get; set; }
public Airport DestinationAirport { get; set; }
public Airport DepartureAirport { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Route>()
.HasKey(i => new { i.DepartureAirportID, i.DestinationAirportID});
modelBuilder.Entity<Route>()
.HasRequired(i => i.DepartureAirport)
.WithMany(u => u.DepartureRoutes)
.HasForeignKey(i => i.DepartureAirportID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Route>()
.HasRequired(i => i.DestinationAirport)
.WithMany(u => u.DestinationRoutes)
.HasForeignKey(i => i.DestinationAirportID)
.WillCascadeOnDelete(false);
}
...这会创建像...这样的表格
CREATE TABLE [Airports] (
[ID] [int] NOT NULL IDENTITY,
[Name] [nvarchar](4000),
CONSTRAINT [PK_Airports] PRIMARY KEY ([ID])
)
CREATE TABLE [Routes] (
[DepartureAirportID] [int] NOT NULL,
[DestinationAirportID] [int] NOT NULL,
CONSTRAINT [PK_Routes] PRIMARY KEY ([DepartureAirportID], [DestinationAirportID])
)
CREATE INDEX [IX_DestinationAirportID] ON [Routes]([DestinationAirportID])
CREATE INDEX [IX_DepartureAirportID] ON [Routes]([DepartureAirportID])
ALTER TABLE [Routes] ADD CONSTRAINT [FK_Routes_Airports_DestinationAirportID] FOREIGN KEY ([DestinationAirportID]) REFERENCES [Airports] ([ID])
ALTER TABLE [Routes] ADD CONSTRAINT [FK_Routes_Airports_DepartureAirportID] FOREIGN KEY ([DepartureAirportID]) REFERENCES [Airports] ([ID])
......你可以像这样使用它......
using (var db = new MyDbContext())
{
foreach (var routeid in Enumerable.Range(1, 100))
{
var departure = new Airport { Name = "departure" + routeid };
db.Airports.Add(departure);
var destination = new Airport { Name = "destination" + routeid };
db.Airports.Add(destination);
var route = new Route{ DepartureAirport = departure, DestinationAirport = destination };
db.Routes.Add(route);
}
int recordsAffected = db.SaveChanges();
foreach (var route in db.Routes)
{
Console.WriteLine("{0}, {1}, {2}, {3}", route.DepartureAirportID, route.DestinationAirportID, route.DepartureAirport.Name, route.DestinationAirport.Name);
}
}
...希望这可以帮助。注意:不要virtual
在必需的属性上使用(因为这些是索引 - 对于这种类型的映射只会像那样工作,我认为你会得到一些错误)。
此外,我总是添加相反的关系,但您可以使用 WithMany() 空白,应该也可以。