How to create a Clustered Index with Entity Framework Core

clustered-index entity-framework entity-framework-core

Question

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?

1
11
1/14/2019 9:31:05 AM

Accepted Answer

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();
21
8/14/2016 4:41:32 PM

Popular Answer

For EF Core 3.0+ You can now use IsClustered:

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

.ForSqlServerIsClustered() is now marked as obsolete.

Also be aware that if you have a Primary Key on the table you may also need to explicitly remove the clustering on it before you add the clustering on your Username:

modelBuilder.Entity<Person>()
.HasKey(e => e.PersonId)
.IsClustered(false);

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


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow