miguelarcilla
miguelarcilla

Reputation: 1456

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

Upvotes: 6

Views: 4094

Answers (1)

Peter Szekeli
Peter Szekeli

Reputation: 2800

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

Upvotes: 8

Related Questions