实体框架代码首要关键一对一关系 [英] One to One Relationship on Primary Key with Entity Framework Code First

查看:221
本文介绍了实体框架代码首要关键一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当尝试使用Code First创建一对一关系时,我正在收到以下错误:
System.Data.Edm.EdmAssociationEnd::多重性在关系'C001_Holding_Teste_C001_Holding中的角色'C001_Holding_Teste_C001_Holding_Source'中无效。因为依赖角色是指关键属性,所以从属角色的多重性的上限必须为1.
我的实体定义如下:

I'm currently getting the following error when trying to create an one to one relationship using Code First: System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'C001_Holding_Teste_C001_Holding_Source' in relationship 'C001_Holding_Teste_C001_Holding'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be 1. My entity definitions are the following:

[Table("C001_Holding", Schema = "Cad")]
public partial class C001_Holding
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int C001_Id { get; set; }

    [MaxLength(16)]
    public string C001_Codigo { get; set; }

    [MaxLength(100)]
    public string C001_Descricao { get; set; }
}

public class C001_Holding_Test
{
    [Key]
    public int C001_Id { get; set; }
    [MaxLength(100)]
    public string C001_TestInfo { get; set; }

    [ForeignKey("C001_Id")]
    public virtual C001_Holding C001_Holding { get; set; }
}

我不想使用流利来创建这些关系,有没有人知道为什么会发生这种情况?

I didn't want to use Fluent to create these relationships, does anyone knows why this is happening?

Tks。

推荐答案

可能将 ForeignKey 属性放在导航属性上,然后指定要作为外键的属性的名称(这就是您所做的)。或者您可以将其放在外键属性上,然后指定代表关系的导航属性的名称。这将是:

It is possible to place the ForeignKey attribute either on a navigation property and then specify the name of the property you want to have as the foreign key (that's what you did). Or you can place it on the foreign key property and then specify the name of the navigation property which represents the relationship. This would look like:

public class C001_Holding_Test
{
    [Key]
    [ForeignKey("C001_Holding")]
    public int C001_Id { get; set; }

    [MaxLength(100)]
    public string C001_TestInfo { get; set; }

    public virtual C001_Holding C001_Holding { get; set; }
}

由于某种原因,第二个选项工作,而第一次抛出错误。 (感觉就像是一个bug,因为这两个选项应该代表相同的关系,或者实际上是一个语义差异,我看不到...)

For some reason this second option works while the first throws an error. (It feels like a bug to me because both options should represent the same relationship. Or there is actually a semantic difference which I don't see...)

这篇关于实体框架代码首要关键一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆