简体   繁体   English

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

[英]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.

相关问题 实体框架两个外键作为主键 - Entity Framework Two foreign keys as primary key 在实体框架中定义外键 - Defining Foreign keys in Entity Framework 如何在Entity Framework中创建由外键组成的复合主键? - How can I create a composite primary key consisting of foreign keys to two tables in Entity Framework? 如何在实体框架代码中首先从表的主键制作两个外键 - How to make two foreign keys from a primary key of a table in Entity Framework Code First 实体框架-由3个外键组成的复合主键 - Entity Framework - Composite Primary Key formed by 3 Foreign Keys 实体框架数据建模:2个外键和一个主键 - Entity Framework data modelling: 2 foreign keys and a primary key Entity Framework Core - 复合键和外键作为主键 - Entity Framework Core - Composite and Foreign Keys as Primary Key 首先在实体框架代码中定义外键 - Defining Foreign Key in Entity Framework Code First 如何将第一个表的主键值更新为第二个表的外键(实体框架代码第一个模型)? - How to update primary key values of first table into foreign keys in the second table (Entity framework code first model)? 在实体框架中将多个外键设置为主键 - set multiple foreign keys as primary keys in entity framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM