HasKey Method in EF Core

HasKey is a Fluent API method, which allows us to configure the primary key & composite primary of an entity in EF Core. This tutorial shows you how to use HasKey in EF Core.

Primary Key

The default convention in EF Core uses the property with the name id or with the name <className>ID. In the absence of such properties, it will not create the table but raises an error

There are two ways you can create the primary key, one is using the Primary Key Attribute. The other way is to use the HasKey method

The following code configures the EmployeeCode as the Primary Key.

HasKey Method in EF Core

Composite Primary Key

A primary key that consists of more than one column is called a Composite Primary key. Default conventions or Key attributes in Data Annotations do not support the creation of Composite Primary keys in EF Core.

The only way we can create it is by using the HasKey method.

In the following model, we want both CompanyCode & EmployeeCode to be part of the primary key.

We create the anonymous type consisting of the above properties and pass it as an argument to the HasKey method.

HasKey Method to create composite primary key in EF Core

Difference With HasAlternateKey

The HasAlternateKey method is similar to the HasKey method. It creates a unique constraint for the property but does not create a Primary key. Unique Constraints ensures that no duplicate values are entered in the columns.

HasKey creates the Primary Key (Which already has a Unique Constraint). But you can have only one Primary Key in the table.

Reference

HasKey Method

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