The HasAlternateKey method creates the Unique constraint for the property in the database. The Primary Key already has a Unique Constraint defined, but you can have only one Primary Key in the table. Unique Constraints ensure that the user cannot insert duplicate values for the columns.
Table of Contents
HasAlternateKey
Consider the following Model. By Convention, EF Core maps the EmployeeID 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
We can compose an alternative key from multiple columns. In such cases, we need to 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 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