How to create a Clustered Index with Entity Framework Core

Ray picture Ray · Aug 14, 2016 · Viewed 16.8k times · Source

From EF6.1, we have a way of specifying a clustered index on a property

public class Person 
{
  [Index(IsClustered = true, IsUnique = true)]
  public long UserName { get; set; }
}

But this Index attribute does not seem to be in EF Core right now? In EF Core how do you achieve this?

Answer

Ivan Stoev picture Ivan Stoev · Aug 14, 2016

From the current EF Core documentation - Indexes section:

Data Annotations

Indexes can not be created using data annotations.

But for sure you can specify that via Fluent API (note the extension methods having ForSqlServer prefix which seem to denote SqlServer specific features):

modelBuilder.Entity<Person>()
    .HasIndex(e => e.UserName)
    .IsUnique()
    .ForSqlServerIsClustered();

Update: for EF Core 3.0+ the method is called just IsClustered:

modelBuilder.Entity<Person>()
    .HasIndex(e => e.UserName)
    .IsUnique()
    .IsClustered();

Update: Starting with EF Core 5.0, there is Index data annotation now mentioned in the Indexes documentation link, but it can't be used to specify database specific attributes like clustered (SqlServer specific), so the original answer still applies.