Entity-framework – One to One Relationship on Primary Key with Entity Framework Code First

ef-code-firstentity-framework

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.

Best Answer

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