Creating a composite primary key in Entity Framework 4.1

19th Jun 2013

There are two main ways of achieving this. Let's look at an object - Brochure: { ProductId, Year, Month, ProductName}. We want:

  • ProductId
  • Year
  • Month

To make up the primary key.

Method 1 - Data annotations

In your entity class, simply decorate any properties that you want to make up your key with the attribute "Key":

public class Brochure 
{
[Key, Column(Order = 0)]
public int ProductId { get; set; }

[Key, Column(Order = 1)]
public int Year { get; set; }

[Key, Column(Order = 3)]
public int Month { get; set; }

[Required]
public string ProductName { get; set; }
}

Method 2 - DbMigration class

NOTE: You shouldn't need to use this method if you are using full entity framework code first. However, some projects only use entity framework to handle migrations - so this might be of use to you:

public partial class BrochureTable : DbMigration 
{
public override void Up()
{
CreateTable("Brochures", c => new
{
ProductId = c.Int(nullable: false),
Year = c.Int(nullable: false),
Month = c.Int(nullable: false),
ProductName = c.String(maxLength: 60)
}
).PrimaryKey(bu => new {bu.ProductId, bu.Year, bu.Month});
}
}

Enjoy!