Data Annotations - Key Attribute in EF 6 & EF Core

The Key attribute can be applied to a property in an entity class to make it a key property and the corresponding column to a PrimaryKey column in the database. The default convention creates a primary key column for a property whose name is Id or <Entity Class Name>Id. The Key attribute overrides this default convention.

using System.ComponentModel.DataAnnotations;

public class Student
{
    [Key]
    public int StudentKey { get; set; }
    public string StudentName { get; set; }
}

As you can see in the above example, Key attribute is applied to StudentKey property of the Student entity class. This will override default conventions and create a primary key column StudentKey in the Students table in the database as shown below.

data annotations key attribute

The Key attribute can be applied to a property of any data type except unsigned integers, e.g. string, datetime, decimal etc.

EF 6:

In EF 6, the Key attribute along with Column attribute can be applied to multiple properties of an entity class which will create composite primary key columns in the database.

EF Core does not support creating a composite key using Key attribute. You have to use Fluent API HasKey() function in EF Core.

using System.ComponentModel.DataAnnotations;

public class Student
{
    [Key]
    [Column(Order=1)]
    public int StudentKey { get; set; }
     
    [Key]
    [Column(Order=2)]
    public int AdmissionNum { get; set; }
     
    public string StudentName { get; set; }
}

The above code creates composite primary key columns StudentKey and AdmissionNum in the Students table as shown below.

data annotations key attribute

Note: In EF 6, Key attribute creates a PK with identity column when applied to a single integer type property. Composite key does not create an identity column for integer property.