3

I'm almost there. The closer I got is a 1 to 0..1 relationship.

My physical schema is:

User: 
 - Id : int primary Key identity
 - Name : varchar(50)

UserDetail: 
 - Id : int primary Key | foreign key to User.Id
 - DisplayName : varchar(200)

When I import this schama in the Entity Data Model Designer, Visual Studio 2010 suggests a 1 to 0..1 relationship. If I enforce 1..1 it accepts but the result doesn't look like a 1..1 relationship.

What do I expect from a 1..1 relationship?

I expect it to either:

  • Automatically create a User when I create a UserDetail and vice-versa (preferable)
  • Throw an exception when I try to save a User without a UserDetail and vice-versa

How can I accomplish that?

Andre Pena
  • 56,650
  • 48
  • 196
  • 243
  • As far as I know it's not possible with todays version of EF, you could however create business logic to enforce this before you save it to the database. – Joakim Jun 05 '11 at 13:00
  • @Joakim: Thanks, but why does the EDMX designer allow me to say it's a 1x1 relationship if it's not supported? As to EF, what's the difference from 1x1 to 1x0..1? – Andre Pena Jun 05 '11 at 13:06
  • just found this question http://stackoverflow.com/questions/1761362/entity-framework-one-to-one-mapping-issues , which shows that I might have been wrong and have to excuse my lack of knowledge. – Joakim Jun 05 '11 at 15:28

1 Answers1

7

It is not supported even on the database level because real 1 to 1 relation mean that you must have FK from User to UserDetail and in the same time FK from UserDetail to User. 1 to 1 says that one record cannot exists without the second record but that makes impossible to insert those record to tables when referential constraints are checked.

One-to-one is in reality always 1 to 0..1 because you must be able to insert principal record without the dependent one and once the principal record is persisted you can insert the dependent one. EF is closely related to the way how relation database works. The only situation I'm aware of where pure 1 to 1 works is table splitting where you map to entities to the same table so both entities always must exist and be inserted together because they form single record.

If you want to always save User and UserDetail together you should model them as single entity using Entity splitting.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670