Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primary Key based on Foreign Keys EF

In the beginning I've tried, as below, but still without result:

  • Defining two foreign keys as primary key in Entity Framework
  • Entity Framework Two foreign keys as primary key

Here is my entity:

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

I am trying to create primary key based on two foreign keys. There is an error

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

What am I doing wrong?

like image 743
miechooy Avatar asked Jan 24 '26 09:01

miechooy


2 Answers

Quoting directly from your first link:

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

So, you need to put the key attributes on the scalar values, not the navigation properties.

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; }
}
like image 103
Paul Abbott Avatar answered Jan 26 '26 02:01

Paul Abbott


As one of quoted 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; }
    //...
}

I noticed now that you are using those attributes on the navigation properties, as @PaulAbbott said in his answer, the primary keys must be defined using scalar properties, in this case, the FK properties.

like image 27
octavioccl Avatar answered Jan 26 '26 02:01

octavioccl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!