Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I establish a one to one relationship with Entity Framework Code First

I've been reading all the Google and SO pages about people who are establishing a one to one relationship in EF but it just isn't working for me.

Here is my model:

Account:

public int Id {get; set;}
public virtual AccountConfig AccountConfig {get; set;}

Account Map:

HasKey(t => t.Id);
HasRequired(t => t.AccountConfig)
    .WithOptional();

Account Config:

public int Id {get; set;}
public int AccountId {get; set;}
public virtual Account Account {get; set;}

Account Config Map:

HasKey(t => t.Id);
HasRequired(t => t.Account)
    .WithOptional(t => t.AccountConfig);

When executed, the AccountConfig property on Account is NULL and the Account property on AccountConfig is an incorrect record (coincidentally, the retrieved Account.Id is the same as the AccountConfig.Id, but I don't know if that means anything).

In the database, the Account table doesn't have a reference to the AccountConfig record but the AccountConfig table has a reference to the Account record using the AccountId column.

The end result would be for me to have a reference to the AccountConfig from Account and (if possible), a reference to Account from AccountConfig.

like image 533
jermny Avatar asked Mar 21 '13 14:03

jermny


1 Answers

With EF, one-to-one relationships are only supported on tables that share a primary key. Your AccountConfig table has its own primary key, and a foreign key to Account. EF only supports a one-to-many relationship with this configuration.

This article has a nice explanation of 1:1 and 1:0..1 relationships in EF. The restriction here is a by-product of the fact that EF doesn't yet support unique constraints.

like image 144
Olly Avatar answered Nov 15 '22 12:11

Olly