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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With