Entity Framework Core Interview Question #94

What are alternate keys in EF Core?

Migrations, Database Schema & Data Management Mid-Level Intermediate

Quick Interview Answer

An alternate key is an additional candidate key that uniquely identifies an entity besides its primary key. EF Core relationships can target an alternate key.

Detailed Explanation

An alternate key is an additional candidate key that uniquely identifies an entity besides its primary key. EF Core relationships can target an alternate key.

Alternate keys are more than ordinary unique indexes because EF Core treats them as keys in the model and can use them as relationship principals.

If uniqueness alone is required and no relationship needs to target the value as a key, a unique index is often sufficient.

Code Example

modelBuilder.Entity<Product>()
    .HasAlternateKey(p => p.ProductCode);