How to create a clustered index with an Entity Framework core base

From EF6.1 we have a way to specify a clustered index on a property

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

But does this Index attribute seem to be missing in the EF Core right now? Or how to do it in EF Core to achieve this? Thank.

+4
source share
2 answers

From the current documentation of the EF Core - Indexes section:

Data Annotations

Indexes cannot be created using data annotations.

But you can certainly specify this via the Fluent API (pay attention to extension methods with a prefix ForSqlServer, which seem to denote the specific functions of SqlServer):

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

OnModelCreating():

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    foreach (var entity in modelBuilder.Model.GetEntityTypes())
    {
        foreach (var prop in entity.GetProperties())
        {
            var attr = prop.PropertyInfo.GetCustomAttribute<IndexAttribute>();
            if (attr != null)
            {
                var index = entity.AddIndex(prop);
                index.IsUnique = attr.IsUnique;
                index.SqlServer().IsClustered = attr.IsClustered;
            }
        }
    }
}

:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class IndexAttribute : Attribute
{
    public bool IsUnique { get; set; } 
    public bool IsClustered { get; set; } 
}

:

public class User
{
    public int UserId { get; set; }
    [Index(IsUnique = true, IsClustered = true)]
    public string Nickname { get; set; }
}
0

Source: https://habr.com/ru/post/1651213/


All Articles