Entity Framework Pitfalls – Composite Primary Keys

When you have a composite primary key, you will get two properties on your POCO class that together represent the id. In this case, conventions won’t be enough, so you need to mark both properties with the KeyAttribute attribute:

public class MyCompositeEntity
{
    [Key]
    public int PartialKey1 { get; set; }
 
    [Key]
    public int PartialKey2 { get; set; }
}

That won’t suffice, though. You also need to specify the order by which the columns should be used, through the ColumnAttribute’s Order property:

public class MyCompositeEntity
{
    [Key]
    [Column(Order = 0)]
    public int PartialKey1 { get; set; }
 
    [Key]
    [Column(Order = 1)]
    public int PartialKey2 { get; set; }
}

Mind you, the order is zero-based. It will be used in two places:

  • When generating the primary key index;
  • When querying using the Find method of the DbSet<T>:
var entity = ctx.MyCompositeEntities.Find(
    1,    //PartialKey1 (Order = 0)
    2     //PartialKey2 (Order = 1)
);

                             

1 Comment

Add a Comment

As it will appear on the website

Not displayed

Your website