Entity Framework Core HasAlternateKey Method

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.

HasAlternateKey

Consider the following Model. By Convention, EF Core maps the EmployeeID as the Primary Key. 

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

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. 

Entity Framework Core Fluent API HasAlternateKey Method Composite AlternateKey

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

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