C# 如何首先与实体框架代码建立一对一关系

C# 如何首先与实体框架代码建立一对一关系,c#,.net,entity-framework,entity,C#,.net,Entity Framework,Entity,我一直在阅读所有关于人们在EF中建立一对一关系的Google和SO页面,但这对我来说根本不起作用 这是我的模型: 账户: public int Id {get; set;} public virtual AccountConfig AccountConfig {get; set;} 帐户映射: HasKey(t => t.Id); HasRequired(t => t.AccountConfig) .WithOptional(); 帐户配置: public int Id

我一直在阅读所有关于人们在
EF
中建立一对一关系的Google和SO页面,但这对我来说根本不起作用

这是我的模型:

账户:

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;}
帐户配置映射:

HasKey(t => t.Id);
HasRequired(t => t.Account)
    .WithOptional(t => t.AccountConfig);
执行时,
Account
上的
AccountConfig
属性是
NULL
,而
AccountConfig
上的
Account
属性是错误的记录(巧合的是,检索到的
Account.Id
AccountConfig.Id
相同,但我不知道这是否意味着什么)

在数据库中,
Account
表没有引用
AccountConfig
记录,但是
AccountConfig
表使用
AccountId
列引用了
Account
记录


最终的结果是,我可以从
Account
中引用
AccountConfig
,并且(如果可能的话)从
AccountConfig

中引用
Account
,对于EF,只有共享主键的表才支持一对一关系。您的
AccountConfig
表有自己的主键和
Account
的外键。EF仅支持与此配置的一对多关系


对EF中的1:1和1:0..1关系有很好的解释。这里的限制是这样一个事实的副产品。

因此,如果Account表有一个名为AccountConfigId?的列,则我只能从Account中引用AccountConfig表,但不完全是这样。您的
AccountConfig
实体应该只有一个
Id
列;删除
AccountId
列,并确保
Id
不是自动生成的。当添加
AccountConfig
实体时,它们的
Id
s应明确设置为与
Account
表记录的
Id
相同。请参阅我链接的文章,以获取与您非常相似的示例。如果我在5小时前找到此答案,我将节省5小时。摇摇头