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
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 is by 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 and pass it as an 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; } } |
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
Read More
- Entity Framework Core Tutorial
- Fluent API Entity Framework Core
- Ignore Method
- HasAlternateKey
- HasKey
- EntityType Configuration
- ForeignKey Attribute
- Conventions in Entity Framework Core
- Data Annotations in entity Framework CoreÂ
- Relationships & Navigational Properties
- One to One Relationships
- One to Many Relationships
- Many To Many Relationships