5

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.

rhughes
  • 9,257
  • 11
  • 59
  • 87
jermny
  • 870
  • 2
  • 12
  • 23

1 Answers1

9

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.

Community
  • 1
  • 1
Olly
  • 5,966
  • 31
  • 60
  • 1
    So I'd only be able to reference the AccountConfig table from Account if the Account table has a column called AccountConfigId? – jermny Mar 21 '13 at 14:10
  • Not exactly. Your `AccountConfig` entity should have only an `Id` column; remove the `AccountId` column and ensure that `Id` is not auto-generated. When adding `AccountConfig` entities, their `Id`s should explicitly be set to be the same as the `Id` of the `Account` table record. – Olly Mar 21 '13 at 14:14
  • See the article I've linked for an example that's quite similar to yours. – Olly Mar 21 '13 at 14:15
  • If I would have found this answer 5 hours ago, I would have saved myself 5 hours. *shaking my head* – Moismyname Apr 09 '14 at 16:19