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

I have an Entity with a name Member

that I would like to set the primary key for MemberId

and GroupId

. In this case, it GroupId

is the primary key of the object 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 add a foreign key column to create 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; }
}

      

+3


source to share


1 answer


Here's an example from MSDN . Just use annotation [Key]

for all the properties you want to include in the composite key and add an additional attribute [Column(Order=x)]

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

      

+5


source







All Articles