The HasAlternateKey method creates the Unique constraint for the property in the database. The Primary Key already has Unique Constraint defined, but you can have only one Primary Key in the table. Unique Constraints ensures that no duplicate values are entered in the columns.
Table of Contents
HasAlternateKey
Consider the following Model. By Convention, the EmployeeID is mapped as the Primary Key.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class Employee { public int EmployeeID { get; set; } public int BranchCode { get; set; } public int EmployeeCode { get; set; } public string Name { get; set; } public DateTime DOB { get; set; } public int Age { get; set; } } |
But we would like to ensure that the EmployeeCode must also be Unique. i.e no two employees should have the same Employee Code. This is the ideal case to use HasAlternateKey
1 2 3 4 5 6 7 | protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Employee>() .HasAlternateKey(e=> e.EmployeeCode); } |
Update the database and you will see that the UNIQUE Constraint is added for the property EmployeeCode. The Constraint is named as AK_<EntityName>_<PropertyName>

Composite Alternate Keys
The alternative key can be composed of multiple columns. In such cases, we need use an anonymous object as the argument to the HasAlternateKey as shown below.
1 2 3 4 | modelBuilder.Entity<Employee>() .HasAlternateKey(e => new { e.BranchCode, e.EmployeeCode }); |

The Constraint follows the naming convention as AK_<EntityName>_<PropertyName1>_<PropertyName2> as shown in the image above
Data Annotations
There is no direct alternative to the HasAlternateKey method in data annotations or in default convention
The Entity Framework core automatically creates an Alternate key if you define a relationship on any property, which is not the primary key