Skip to content

EF Core Index Attribute — Complete Guide

DodaTech Updated 2026-06-24 1 min read

In this tutorial, you'll learn about EF Core Index Attribute. We cover key concepts, practical examples, and best practices.

You add an index on a property using Fluent API, but you have to dig into OnModelCreating to find or modify it.

Wrong

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Product>()
        .HasIndex(p => p.Category);
}
// Index is defined far from the entity class
[Index(nameof(Category))]
[Index(nameof(Name), nameof(Price), IsUnique = true)]
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

Composite and unique:

[Index(nameof(Email), IsUnique = true)]
[Index(nameof(FirstName), nameof(LastName))]
public class User { ... }

Prevention

  • Use [Index] attribute on entity classes for simple indexes.
  • Supports composite indexes by specifying multiple property names.
  • Set IsUnique = true for unique constraints.
  • Set Name = "IX_MyIndex" for custom index names.
  • Set IsDescending = new[] { true, false } for mixed sort order.

Common Mistakes with core index attribute

  1. Using head and tail instead of pattern matching, causing runtime errors on empty lists
  2. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  3. Using return to exit a function early instead of wrapping a pure value in the monad

These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

Can I use the Index attribute for filtered indexes?

No. Use Fluent API `HasFilter` for filtered indexes. The Index attribute does not support filter conditions.
Does the Index attribute support included columns?

No. Use Fluent API for included (covering) columns in SQL Server.

Can I create indexes on shadow properties?

Yes, but you must use Fluent API. The Index attribute only works with explicit properties.

For more EF Core configuration, visit DodaTech.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro