Defining two foreign keys as a primary key in the Entity Framework

In the Entity Framework, I would like to use two foreign keys as the primary key of another type of object.

public class CustomerExtensionValue {

    // Values for extended attributes of a customer
    [Key]
    [Column(Order = 0)]
    public Customer Customer { get; set; }

    [Key]
    [Column(Order = 1)]
    public CustomerExtension Extension { get; set; }

    [Required]
    public string Value { get; set; }
}

However, this gives me an error that the key will be missing. \tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'CustomerExtensionValue' has no key defined. Define the key for this EntityType.

I know that I could define two more attributes containing primary keys of reference entity types. Is Visual Studio smart enough to use its primary keys on its own?

+3
source share
1 answer

Primary keys must always be determined by scalar properties in the entity class. You cannot reference PK only using navigation properties. Your model requires this definition:

public class CustomerExtensionValue {

    [Key, ForeignKey("Customer"), Column(Order = 0)]
    public int CustomerId { get; set; }

    [Key, ForeignKey("Extension"), Column(Order = 1)]
    public int ExtensionId { get; set; }

    public Customer Customer { get; set; }
    public CustomerExtension Extension { get; set; }

    [Required]
    public string Value { get; set; }
}
+6
source

All Articles