简体   繁体   中英

How to do a true one-to-one relationship in Entity Framework?

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM