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

4k views Asked by At

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

There are 1 answers

0
Peter Szekeli On BEST ANSWER

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