RSS

Composite Key (Multi Columns Primary Key) in EF Code First

11 Jun

Composite Key is basically Primary Key that spans multiple columns. Look like this:

composite-key-multi-columns-primary-key-in-ef-code-first-1

composite-key-multi-columns-primary-key-in-ef-code-first-2

To achieve this in EF Code First, all you need to add is Key and Column data annotation. (I am using Entity Framework 6).

Column attribute takes in Order parameter which you can use to specify the order as it appears on the table.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class Employee
{
    [Key]
    [Column(Order = 1)]
    public int Id { get; set; }

    [Key]
    [Column(Order = 2)]
    public Guid DepartmentId { get; set; }

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

    public string Firstname { get; set; }
    public string Lastname { get; set; }
}
Advertisements
 
2 Comments

Posted by on June 11, 2015 in General

 

Tags: ,

2 responses to “Composite Key (Multi Columns Primary Key) in EF Code First

  1. Osley Hernandez calvo

    March 13, 2017 at 11:55 am

    Thanks a lot for your article, it has saved my life!!!

     
  2. Abner

    June 30, 2017 at 12:51 am

    Could you please explain the correct way to reference this composite key as a foreign key from another model.

    for example if you had a class, TEAM, and team had an employee as a team leader.

    if the employee class had a single key i would do it as follows:

    Public Class Team
    {
    [Foreign key(EmployeeModel)]
    public int TeamLeadId { get; set; }

    public Employee EmployeeModel
    }

    Now that employee has multiple keys how would i model this relationship?

     

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

 
%d bloggers like this: