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

.net c# entity entity-framework

Question

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.

1
5
3/21/2013 2:05:45 PM

Accepted Answer

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.

9
5/23/2017 10:33:53 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow