本文介绍了如何与Entity Framework Code First建立一对一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读关于在 EF 中建立一对一关系的人的所有Google和SO页面,但它并不适用于我。 / p>

这是我的模型:



帐户:

  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);

执行时, AccountConfig code>帐户是 NULL 帐户属性 AccountConfig 是一个不正确的记录(巧合的是,检索到的 Account.Id AccountConfig.Id ,但我不知道这是否意味着什么)。



在数据库中,帐户表没有引用 AccountConfig 记录,但$ code> AccountConfig 表中引用了帐户记录使用 AccountId 列。



最终结果对于我来说,请参考 AccountConfig 帐户和(如果可能),引用帐户 AccountConfig

解决方案

使用EF,共享主键的表仅支持一对一的关系。您的 AccountConfig 表具有自己的主键,外键为帐户。 EF只支持与此配置的一对多关系。




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.

这篇关于如何与Entity Framework Code First建立一对一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-11 01:26