EF Core Index Attribute — Complete Guide
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
Right
[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 = truefor 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
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto 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.For more EF Core configuration, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro