基于外键 EF 的主键

Primary Key based on Foreign Keys EF

一开始试过,如下,还是没有结果:

这是我的实体:

public class Passage
{
        [Key, ForeignKey("FromID")]
        public Localization From { get; set; }

        public int ToID { get; set; }

        [Key, ForeignKey("ToID")]
        public Localization To { get; set; }

        [Required]
        public string HourForm { get; set; }

        [Required]
        public string HourTo { get; set; }

        [Required]
        public int Seats { get; set; }

        [Required]
        public char Weekend { get; set; }

        public int? AdditinalTime { get; set; }

        public int FromID { get; set; }
}

我正在尝试基于两个外键创建主键。有错误

EntityType 'Passage' has no key defined. Define the key for this EntityType.

我做错了什么?

作为引用之一 links said, you need to use the Column attribute to specify the order of your composite keys:

public class Passage
{
    [Key,Column(Order=0), ForeignKey("From")]
    public int FromId { get; set; }

    [Key,Column(Order=1), ForeignKey("To")]
    public int ToId { get; set; }
    //...
}

我现在注意到您在导航属性上使用了这些属性,正如@PaulAbbott 在他的回答中所说,在这种情况下,必须使用 标量属性 定义主键, FK 属性。

直接引用您的第一个 link:

"Primary keys always must be defined by scalar properties in the entity class. You cannot refer to the PKs by navigation properties alone."

因此,您需要将关键属性放在标量值上,而不是导航属性。

public class Passage
{
    [Key, ForeignKey("From"), Column(Order = 0)]
    public int FromID { get; set; }

    public Localization From { get; set; }

    [Key, ForeignKey("To"), Column(Order = 1)]
    public int ToID { get; set; }

    public Localization To { get; set; }
}