Entity Framework Core Interview Question #92

How do you create a unique index in EF Core?

Migrations, Database Schema & Data Management Mid-Level Intermediate

Quick Interview Answer

A unique index enforces that the indexed key value or key combination cannot be duplicated according to the database's uniqueness semantics.

Detailed Explanation

A unique index enforces that the indexed key value or key combination cannot be duplicated according to the database's uniqueness semantics.

It is useful for business identifiers such as a normalized username, product SKU, or subject-specific slug when duplicates are invalid.

Application validation can provide a friendly error message, but the database unique constraint or index is still important because concurrent requests can otherwise bypass a check-then-insert validation pattern.

Code Example

modelBuilder.Entity<Product>()
    .HasIndex(p => p.Sku)
    .IsUnique();