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小时。摇摇头