One to One Relationship on Primary Key with Entity Framework Code First

折月煮酒 提交于 2019-12-31 02:31:10

问题


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.


回答1:


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

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



来源:https://stackoverflow.com/questions/5339951/one-to-one-relationship-on-primary-key-with-entity-framework-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!