Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include foreign key in composite primary key in Code-First Entity Framework

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; }
}
like image 549
miguelarcilla Avatar asked Jun 16 '15 05:06

miguelarcilla


People also ask

Can a foreign key be part of a composite primary key?

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.

How do I add a foreign key in code first approach in .NET core?

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.

Can an entity have a primary key and a foreign key?

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.

How do I create a composite primary key in Entity Framework?

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.


1 Answers

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; }
}
like image 175
Szeki Avatar answered Nov 01 '22 16:11

Szeki