在Entity Framework中将两个外键定义为主键

Exp*_*cat 3 c# entity-framework asp.net-web-api

在Entity Framework中,我想使用两个外键作为另一个实体类型的主键.

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; }
}
Run Code Online (Sandbox Code Playgroud)

但是,这给了我一个错误,即密钥丢失. \tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'CustomerExtensionValue' has no key defined. Define the key for this EntityType.

我知道我可以定义两个包含引用实体类型主键的属性.Visual Studio是否不够智能,无法自己使用主键?

Sla*_*uma 7

主键始终必须由实体类中的标量属性定义.您不能仅通过导航属性来引用PK.在您的模型中,需要这样的定义:

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; }
}
Run Code Online (Sandbox Code Playgroud)