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.
Table of Contents
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
1 2 3 4 5 6 7 | public class Employee { public int EmployeeCode { get; set; } public string Name { get; set; } } |
The following code configures the EmployeeCode
as the Primary Key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public class EFContext : DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { //Configure domain classes using modelBuilder here modelBuilder.Entity<Employee>() .HasKey("EmployeeCode"); } public DbSet<Employee> Employee { get; set; } } |

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.
1 2 3 4 5 6 7 8 | public class Employee { public string CompanyCode { get; set; } public int EmployeeCode { get; set; } public string Name { get; set; } } |
We create the anonymous type consisting of the above properties of and pass it as the argument to the HasKey method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class EFContext : DbContext { protected override void OnModelCreating(ModelBuilder modelBuilder) { //Configure domain classes using modelBuilder here modelBuilder.Entity<Employee>() .HasKey( o=> new { o.CompanyCode, o.EmployeeCode}); } public DbSet<Employee> Employee { get; set; } } |
