Creating a composite primary keys in Entity Framework 4.1

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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s