[英]Defining two foreign keys as primary key in Entity Framework
In Entity Framework, I'd like to use two foreign keys as primary key of another entity type. 在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; }
}
However, this gives me an error that a key would be missing. 但是,这给了我一个错误,即密钥丢失。
\\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'CustomerExtensionValue' has no key defined. Define the key for this EntityType.
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?
Visual Studio是否不够智能,无法自己使用主键?
Primary keys always must be defined by scalar properties in the entity class. 主键始终必须由实体类中的标量属性定义。 You cannot refer to the PKs by navigation properties alone.
您不能仅通过导航属性来引用PK。 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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.