In the beginning I've tried, as below, but still without result:
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?
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; }
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With