Data Annotations Key Attribute in EF Core

The Key Attribute or Primary key attribute maps the property as the primary key column in the database. This attribute is applicable to both Entity Framework & Entity Framework Core. In Entity Framework, we can use it to create Composite Primary key, while in EF Core it is not supported.

Default Convention

The Entity Framework Core Convention look for the property with the name id or with the name  <className>ID. It then maps that property to the Primary Key. In case it finds both id property and  <className>ID property, then id property is used. The following model creates the table with CustomerID As the primary key.

Primary Key Default Convention in EF Core

Key Attribute

You can override this behavior using the Data Annotation Key attribute. The Key attribute marks the property as the Primary Key. This will override the default Primary Key. The following code creates the table with CustomerNo as the Primary key instead if CustomerID

Do not forget to import the following namespace

Key Attribute in Entity Framework Core
Key Attribute in Entity Framework

Note that the CustomerNo column created with the Identity enabled. Key attribute, if applied on the integer column will create the column with the Identity enabled (autoincrement)

The unsigned data types (uint) is allowed in EF Core. It is mapped to bigint. Also, EF Core does not create a Identity column for unsigned data types

Short data type is mapped to SmallInt with Identity column

Key Attribute on a string property

Key Attribute on string data type in Entity Framework Core
Key Attribute on string data type in Entity Framework

Enabling / Disabling identity column

You can disable/enable the identity on the numeric column by using the DatabaseGenerated attribute.

The following code disables the identity column

Key Attribute with identity disabled in EF Core

The following code enables the identity column

Composite Primary Key

The EF Core does not allow creating the Composite Primary key using Key Attribute.

For Example, the following model will result in an error.

EF Core 3.1
The entity type Customer has multiple properties with the [Key] attribute. Composite primary keys can only be set using HasKey in OnModelCreating.

EF Core 2.1
Entity type Customer has the composite primary key defined with data annotations. To set the composite primary key, use fluent API.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top