问题描述
我一直在阅读所有关于人谁是建立一个一对一的 EF
关系,谷歌和SO网页,但它只是不为我工作。
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.
下面是我的模型:
帐号:
public int Id {get; set;}
public virtual AccountConfig AccountConfig {get; set;}
帐户映射:
HasKey(t => t.Id);
HasRequired(t => t.AccountConfig)
.WithOptional();
账号配置:
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);
当执行时,在 AccountConfig
属性帐户
是 NULL
和 AccountConfig
帐户属性>是一个不正确的记录(巧合的是,该检索帐户.ID
是一样的 AccountConfig.Id
,但我不知道这意味着什么)。
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).
在数据库中,帐户
表没有一个参照 AccountConfig
记录,但 AccountConfig
表中有一个引用帐户
使用的AccountId
列纪录
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.
最终的结果将是对我来说,有一个参照 AccountConfig
从帐户
键,(如果可能) ,引用帐户
从 AccountConfig
。
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
.
推荐答案
通过EF,一到一对一的关系只支持共享一个主键的表。你的 AccountConfig
表都有自己的主键,以及一个外键帐户
。 EF仅支持一对许多具有此配置关系
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.
本文有1和1:在EF 0..1关系1很好的解释。这里的限制是这样的事实 EF尚不支持唯一约束的一个副产品。
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.
这篇关于我如何建立与实体框架$ C C首先$一对一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!