I have an Entity named Member
, for which I would like to set a primary key of MemberId
and GroupId
. In this case, GroupId
is the primary key of the entity Group
. With the code below, the foreign key is set correctly, but it is not included as part of the primary key. How can I have the foreign key column added to make a composite primary key?
public class Member
{
[Key]
public string MemberId { get; set; }
public string MemberName { get; set; }
public string GroupId { get; set; }
[ForeignKey("GroupId")]
public virtual Group Group { get; set; }
}
This is not possible. The foreign key can not refer to part of composite primary key of other table. Because it is supposed to be one-to-one relationship and if you refer just part of primary-key, there might be more than one parent record available, which is neither allowed nor possible.
To create Foreign Key, you need to use ForeignKey attribute with specifying the name of the property as parameter. You also need to specify the name of the table which is going to participate in relationship.
Each entity must have a attribute or attributes, the primary key, whose values uniquely identify each instance of the entity. Every child entity must have an attribute, the foreign key, that completes the association with the parent entity.
Entity Framework Core supports composite keys - primary key values generated from two or more fields in the database. Composite keys are not covered by conventions or data annotation attributes. The only way to configure composite keys is to use the HasKey method.
Here's an example from MSDN. Simply use the [Key]
annotation on all the properties you want to include in the composite key and add an extra [Column(Order=x)]
attribute for those columns.
public class Member
{
[Key]
[Column(Order = 0)]
public string MemberId { get; set; }
[Key]
[Column(Order = 1)]
public string GroupId { get; set; }
public string MemberName { get; set; }
[ForeignKey("GroupId")]
public virtual Group Group { get; set; }
}
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