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 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 of and pass it as the argument to the HasKey method.

HasKey Method to create composite primary key in EF Core

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