LiDong Li
LiDong Li

Reputation: 13

Composite-primary key issue in entity framework code first

I have an issue in entity framework code first, three table in database as follows:

CREATE TABLE [Food](
PK [FoodId] [int] NOT NULL,
[FoodName] [varchar](50) NULL)

CREATE TABLE [Fruit](
PK [FruitId] [int] NOT NULL,
[FruitName] [varchar](50) NULL)

CREATE TABLE [FoodFruit](
PK, FK [FoodId] [int] NOT NULL,
PK, FK [FruitId] [int] NOT NULL)

The Model will only generate Food, Fruit entities.

But if I add a new column [Notes] to FoodFruit table, such as Notes:

CREATE TABLE [FoodFruit](
PK, FK [FoodId] [int] NOT NULL,
PK, FK [FruitId] [int] NOT NULL,
[Notes] [varchar](50) NULL)

The Model will generate Food, Fruit and FoodFruit entities.

So, I'm confused it, why the first one doesn't generate the FoodFruit entity.

Upvotes: 1

Views: 557

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364249

That is correct behavior. In the first case your FoodFruit table is just database helper to model many-to-many relationship. EF doesn't need such helper in conceptual model so it hides this table behind directly modeled many-to-many relation. In the second case the table has additional data - it becomes full entity, not just junction table for relationship. EF detects it and map it as a new class.

Upvotes: 2

Related Questions