Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Database first Entity Framework mapping unique foreign keys as one to many

I have a table in Microsoft SQL Server 2008 R2 called Page with a primary key called ID. I have another table called Navigation with a column PageID. PageID is a unique foreign key reference to the ID column of Page. This creates a one to one relationship between Navigation and Page records.

When generating models from the database, it creates a one to many relationship where a Page contains a list of Navigation records.

Is this simply the Entity Framework detecting that there is a foreign key involved and ignoring the uniqueness of the columns in the database?

The SQL for the PageID column in Navigation is:

[PageID] INTEGER FOREIGN KEY REFERENCES [Page](ID) UNIQUE NOT NULL

The SQL for the ID column in Page is:

[ID] INTEGER PRIMARY KEY IDENTITY(0, 1) NOT NULL

Here is the solution I had originally, which is what Ladislav was mentioning.

The SQL for the PageID column in Navigation was:

[ID] INTEGER PRIMARY KEY FOREIGN KEY REFERENCES [Page](ID) NOT NULL
like image 500
Michael J. Gray Avatar asked Apr 08 '12 07:04

Michael J. Gray


People also ask

Where does the foreign key go in one-to-many relationship?

If there is a one-to-many relationship between two entities, add the key of the entity on the “one” side (the parent) into the child table as a foreign key.

How do you set a one-to-one relationship in Entity Framework?

We can configure a one-to-One relationship between entities using Fluent API where both ends are required, meaning that the Student entity object must include the StudentAddress entity object and the StudentAddress entity must include the Student entity object in order to save it.

How do you store a one-to-many relationship in a database?

To define a one-to-many relationship between two tables, the child table has to reference a row on the parent table. The steps required to define it are: Add a column to the child table that will store the value of the primary identifier.


1 Answers

Entity framework doesn't support unique keys yet so this information is really ignored and one to many relation is mapped. The only way to use one to one relation in EF is through shared primary key (Navigation's ID will be FK to Page's ID).

like image 191
Ladislav Mrnka Avatar answered Oct 06 '22 00:10

Ladislav Mrnka