定义两个外键在实体框架的主键

问题描述:

在实体框架,我想用两个外键的另一个实体类型的主键。

In Entity Framework, I'd like to use two foreign keys as primary key of another entity type.

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

然而,这给了我一把钥匙将丢失的错误。 \\ tSystem.Data.Entity.Edm.EdmEntityType:的EntityType'CustomerExtensionValue没有定义键。定义此的EntityType关键。

我知道我可以定义两个拿着引用的实体类型的主键属性。是Visual Studio中没有足够的智慧用​​在自己的主键?

I'm know I could define two more attributes holding the primary keys of the referenced entity types. Is Visual Studio not smart enough to use their primary keys on his own?

主键始终必须通过实体类标量属性进行定义。你不能单靠导航属性指的PK。在你的模型像这样的定义是必需的:

Primary keys always must be defined by scalar properties in the entity class. You cannot refer to the PKs by navigation properties alone. In your model a definition like this is required:

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