簡體   English   中英

在Entity Framework中將兩個外鍵定義為主鍵

[英]Defining two foreign keys as primary key in Entity Framework

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

但是,這給了我一個錯誤,即密鑰丟失。 \\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'CustomerExtensionValue' has no key defined. Define the key for this EntityType.

我知道我可以定義另外兩個屬性來保存被引用實體類型的主鍵。 Visual Studio是否不夠智能,無法自己使用主鍵?

主鍵始終必須由實體類中的標量屬性定義。 您不能僅通過導航屬性來引用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; }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM