Entity Framework Core Interview Question #91

How do you create indexes with EF Core?

Migrations, Database Schema & Data Management Mid-Level Intermediate

Quick Interview Answer

Indexes can be configured in the EF Core model with HasIndex. A migration can then create the corresponding database index.

Detailed Explanation

Indexes can be configured in the EF Core model with HasIndex. A migration can then create the corresponding database index.

Indexes can improve filtering, joining, sorting, and uniqueness checks, but they also consume storage and add work to inserts, updates, and deletes.

Index design should be based on real query patterns and database execution plans rather than adding an index to every column.

Code Example

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

modelBuilder.Entity<Order>()
    .HasIndex(o => new { o.CustomerId, o.CreatedAtUtc });