6

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
Michael J. Gray
  • 9,784
  • 6
  • 38
  • 67

1 Answers1

6

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).

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I tried that originally but was concerned that it was sort of a bad design decision. I suppose we'll be moving back to that. Do you happen to have a reference to a Microsoft page that speaks on EF ignoring unique keys? – Michael J. Gray Apr 08 '12 at 08:31
  • 2
    [Here is blog post](http://blogs.msdn.com/b/efdesign/archive/2011/03/09/unique-constraints-in-the-entity-framework.aspx) about unique constraints in EF from last year. This was preview of feature which could be hopefully implemented in future. It will not be part of upcoming .NET 4.5 / EF 5.0. If you want unique constraints in EF vote for them on [Data UserVoice](http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1050579-unique-constraint-i-e-candidate-key-support). – Ladislav Mrnka Apr 08 '12 at 10:44