Entity Framework Core HasAlternateKey Method

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.

HasAlternateKey

Consider the following Model. By Convention, the EmployeeID is mapped 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

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. 

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 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

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top