如何使用额外的关键部分将实体框架映射到多个表?

时间:2012-03-17 00:46:22

标签: entity-framework

有没有办法对此进行映射,以便父表机场和航班仅映射到外部复合键的相关部分?

将EF4.3与Code First和Fluid API结合使用。

每架航班按特定顺序降落在一个或多个机场。如果没有FlightOrder的附加键属性,则此映射可以正常工作。

Airport
- string Code
- List<AirportFlight> AirportFlights

Flight
- string Number
- List<AirportFlight> AirportFlights

AirportFlight
- string AirportCode
- string FlightNumber
- int FlightOrder

public AirportConfiguration() {
    HasKey(x => x.Code);
    HasMany(x => x.AirportFlights).WithRequired().HasForeignKey(x => x.AirportCode);
}

public AirportFlightConfiguration() {
    HasKey(x => new { x.AirportCode, x.FlightNumber, x.FlightOrder });
}

public FlightConfiguration()
{
    HasKey(x => x.Number);
    HasMany(x => x.AirportFlights).WithRequired().HasForeignKey(x => x.FlightNumber);
}

这是Entity Framework生成的架构:

CREATE TABLE Airports(
Code nvarchar(128) NOT NULL,
AirportFlight_AirportCode nvarchar(128) NULL, -- *** DO NOT WANT THIS ***
AirportFlight_FlightNumber nvarchar(128) NULL, -- *** DO NOT WANT THIS ***
AirportFlight_FlightOrder int NULL, -- *** DO NOT WANT THIS ***

CREATE TABLE Flights(
Number nvarchar(128) NOT NULL,
AirportFlight_AirportCode nvarchar(128) NULL, -- *** DO NOT WANT THIS ***
AirportFlight_FlightNumber nvarchar(128) NULL, -- *** DO NOT WANT THIS ***
AirportFlight_FlightOrder int NULL, -- *** DO NOT WANT THIS ***

CREATE TABLE AirportFlights(
AirportCode nvarchar(128) NOT NULL,
FlightNumber nvarchar(128) NOT NULL,
FlightOrder int NOT NULL,
CreatedDate datetime NOT NULL,
RowVersion varbinary(max) NULL,
CONSTRAINT PK_AirportFlights PRIMARY KEY CLUSTERED 
(
    AirportCode ASC,
    FlightNumber ASC,
    FlightOrder ASC
)

ALTER TABLE AirportFlights  WITH CHECK ADD  CONSTRAINT FK_AirportFlights_Airports_AirportCode FOREIGN KEY(AirportCode)
REFERENCES Airports (Code)

ALTER TABLE AirportFlights  WITH CHECK ADD  CONSTRAINT FK_AirportFlights_Flights_FlightNumber FOREIGN KEY(FlightNumber)
REFERENCES Flights (Number)

-- *** DO NOT WANT THIS ***
ALTER TABLE Airports  WITH CHECK ADD  CONSTRAINT FK_Airports_AirportFlights_AirportFlight_AirportCode_AirportFlight_FlightNumber_AirportFlight_FlightOrder FOREIGN KEY(AirportFlight_AirportCode, AirportFlight_FlightNumber, AirportFlight_FlightOrder)
REFERENCES AirportFlights (AirportCode, FlightNumber, FlightOrder)

-- *** DO NOT WANT THIS ***
ALTER TABLE Flights  WITH CHECK ADD  CONSTRAINT FK_Flights_AirportFlights_AirportFlight_AirportCode_AirportFlight_FlightNumber_AirportFlight_FlightOrder FOREIGN KEY(AirportFlight_AirportCode, AirportFlight_FlightNumber, AirportFlight_FlightOrder)
REFERENCES AirportFlights (AirportCode, FlightNumber, FlightOrder)

感谢。

固定

这些属性位于AirportFlights实体

- List<Airport> Airports
- List<Flight> Flights

1 个答案:

答案 0 :(得分:0)

由于您已将连接表映射为实体,因此它没有AirportFlight的集合导航属性。您必须将其建模为两个一对多关系。移除List<Airport> AirportsList<Flight> Flights

AirportFlight
- string AirportCode
- string FlightNumber
- int FlightOrder

但是,如果您愿意,可以在Airport实体上放置导航功能FlightAirportFlight